首页 > 解决方案 > 合并列以创建带有标题的日期

问题描述

我正在使用一个大型气候文件,其中有 YYYY、MM、DD 列。我想合并这些以创建一个日期列,同时将所有原始数据保留在数据集中。

到目前为止,我已经设法做到了这一点,这几乎得到了我想要的东西,但我似乎无法在日期列中找到标题。

climate = pd.read_csv(r'R:\Climate\SILO\PatchedPoint\Current_csv\86090.csv')

climate.apply(pd.to_numeric, errors = 'ignore')
climate_nozero = climate.drop([0])

climate2 = climate_nozero.rename(columns = {'YYYY':'Year','MM':'Month','DD':'Day'})

index = climate2.apply(lambda x: pd.datetime.strptime("{0} {1} {2}".format(x['Year'],x['Month'], x['Day']), "%Y %m %d"),axis=1) 

climate3 = pd.concat([index, climate2], axis=1)

我试过

climate4 = climate3.rename(columns = {'0':'Date'})

更改标题,但它什么也不做

我添加了我得到的输出表

标签: pythonpandasdataframeheader

解决方案


假设您的日期列是字符串,您可以像这样assign()使用to_datetime()

df.assign(date = pd.to_datetime(df['YYYY'] + "-" + df['MM'] + "-" + df['DD']))

   YYYY  MM DD  foo       date
0  2010   5  1    0 2010-05-01
1  2012  10  2    1 2012-10-02
2  2015  12  3    2 2015-12-03

数据:

data = {"YYYY": ["2010", "2012", "2015"], 
        "MM": ["5", "10", "12"], 
        "DD": ["1", "2", "3"],
        "foo": range(3)}

df = pd.DataFrame(data)

推荐阅读