Python 合并列以创建带有标题的日期
我使用的是一个大气候文件,其中有YYYY、MM、DD列。我希望合并这些数据以创建一个日期列,同时保留数据集中的所有原始数据 到目前为止,我已经设法做到了这一点,这几乎满足了我的需求,但我似乎无法在日期列中找到标题Python 合并列以创建带有标题的日期,python,pandas,dataframe,header,Python,Pandas,Dataframe,Header,我使用的是一个大气候文件,其中有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 = 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'})
更改标题,但它不执行任何操作
concat和rename我建议直接将列分配给数据框中的命名字段。我认为以下内容可以替代你的底线:
climate2["Date"] = climate2.apply(lambda x: pd.datetime.strptime("{0} {1} {2}".format(x['Year'],x['Month'], x['Day']), "%Y %m %d"),axis=1)
假设您的日期列是字符串,您可以这样使用:
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)}
climate_nozero = pd.DataFrame(data)
climate2 = climate_nozero.rename(columns = {'YYYY':'Year','MM':'Month','DD':'Day'})
climate2.index = pd.to_datetime(climate2[['Year','Month','Day']])
print (climate2)
Year Month Day foo
2010-05-01 2010 5 1 0
2012-10-02 2012 10 2 1
2015-12-03 2015 12 3 2
如果要删除列,请执行以下操作:
climate2 = climate2.drop(['Year','Month','Day'], axis=1)
print (climate2)
foo
2010-05-01 0
2012-10-02 1
2015-12-03 2
如果需要datetime列:
climate2['date'] = pd.to_datetime(climate2[['Year','Month','Day']])
print (climate2)
Year Month Day 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
感谢这项工作,然后我只是把日期列作为索引。
climate2['date'] = pd.to_datetime(climate2[['Year','Month','Day']])
print (climate2)
Year Month Day 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