Python如何计算一个日期值列表的多少个月

2024-05-07 07:08:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,正在练习。我有两列的列表,第一列包含日期值,第二列包含数值。因此,我需要计算从第一列开始的月份数,并根据日期值对第一列从最早日期到最新日期进行排序。你知道吗

到目前为止,我的情况是:

import os

import csv

source_csv = os.path.join("..","C:/Users/Desktop/","data.csv")

with open(source_csv,newline="") as csvfile:

    csvreader = csv.reader(csvfile,delimiter=",")
    next(csvreader)  # skip the headers

    sortedlist = sorted(csvreader, key=lambda row: row[0], reverse = True)
    print(sortedlist)

my list:


Tags: csvcsvfilepathimportsource列表排序os
1条回答
网友
1楼 · 发布于 2024-05-07 07:08:15

使用pandas和datetime包,操作非常简单

import pandas as pd
#Read the data
df=pd.read_csv('tempdata.csv')

#Convert to a  Date format here
df['NewDate']=df['Date'].apply(lambda x: datetime.strptime(x, '%m/%d/%y'))

#Extract Month and store as new column
df['Month']=df['NewDate'].apply(lambda x: x.month)

#Sort the data frame in descending dates
df.sort_values('NewDate')

enter image description here

相关问题 更多 >