Rah*_*tia 0 python numpy python-2.7 python-3.x pandas
我有一个DataFrame18列和大约10000行的熊猫.
我的第一个3列有不同的值YEAR,MONTH和DAY.我需要合并这三列,并将所有行的整个日期放在一列中.
到目前为止我的代码是:
df.merge('Year','/','Month')
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
该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
Run Code Online (Sandbox Code Playgroud)
您可以将这些作为列添加到数据框中,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
.
值得注意的是,大熊猫parse_dates在阅读csv时有一个简单的方法.
| 归档时间: |
|
| 查看次数: |
2054 次 |
| 最近记录: |