我在从CSV文件导入的熊猫数据框中有以下列。我想添加两列,分别包含小时和星期几。
输入:
+-------------------+
| date |
+-------------------+
|2018/08/26 7:30:26|
+-------------------+
|2018/05/12 8:10:26|
+-------------------+
|2018/11/16 14:36:26|
+-------------------+
|2018/12/06 17:40:26|
+-------------------+
输出必须为:
+-------------------+----------+------+
| date-time | date | hour |
+-------------------+----------+------+
|2018/08/26 7:30:26|2018/08/26| 7 |
+-------------------+----------+------+
|2018/05/12 8:10:26|2018/05/12| 8 |
+-------------------+----------+------+
|2018/11/16 14:36:26|2018/11/16|14 |
+-------------------+----------+------+
|2018/12/06 17:40:26|2018/12/06|17 |
+-------------------+----------+------+
答案 0 :(得分:4)
您可以使用dt
访问器从日期时间值中获取date
和hour
:
df.date = pd.to_datetime(df.date)
df = df.rename(columns = {'date':'datetime'})
df.assign(date = df.date.dt.date, hour = df.date.dt.hour)
datetime date hour
0 2018-08-26 07:30:26 2018-08-26 7
1 2018-05-12 08:10:26 2018-05-12 8
2 2018-11-16 14:36:26 2018-11-16 14
3 2018-12-06 17:40:26 2018-12-06 17