组合DataFrame中的行

时间:2012-12-07 05:06:23

标签: python numpy python-3.x python-2.7 pandas

我有一个有18列和大约10000行的panda DataFrame

我的前3列有YEARMONTHDAY的单独值。我需要合并这三列,并将所有行的整个日期放在一列中。

到目前为止我的代码是:

df.merge('Year','/','Month')

1 个答案:

答案 0 :(得分:5)

您正在寻找apply merge就像数据库加入一样。):

In [1]: from pandas import DataFrame

In [2]: df = DataFrame([[1,11,2012],[1,10,2012]], columns=['day','month','year'])

In [3]: df
Out[3]: 
   day month  year
0    1    11  2012
1    1    10  2012

In [4]: df.apply(lambda row: str(row['day'])+'/'+str(row['month'])+'/'+str(row['year']), axis=1)
Out[4]: 
0    1/11/2012
1    1/10/2012

axis=1部分表示您正在选择列而不是行。

如果您想提供特定日期,可以使用日期时间:

In [5]: import datetime

In [6]: df.apply(lambda row: datetime.datetime(row['year'],row['month'],row['day']), axis=1)
Out[6]: 
0    2012-11-01 00:00:00
1    2012-10-01 00:00:00

您可以将这些作为列添加到数据框中,如下所示:

In [7]: df['new_date'] = df.apply(lambda row: str(row['day'])+'/'+str(row['month'])+'/'+str(row['year']), axis=1)

In [8]: df
Out[8]: 
   day month  year   new_date
0    1    11  2012  1/11/2012
1    1    10  2012  1/10/2012

值得注意的是,大熊猫可以轻松地parse_dates when reading as a csv