使用熊猫,我可以通过mySeries.dt.date
将日期时间序列转换为日期序列。
一个numpy列的外观如何?示例:
import pandas as pd
df = pd.DataFrame({"a": ["31.12.1999 23:59:12", "31.12.1999 23:59:13", "31.12.1999 23:59:14"], "b": [4, 5, 6]})
df["datetime"] = pd.to_datetime(df.a)
df["date"]=df.datetime.dt.date
print("df.columns:", df.columns)
df.columns: Index(['a', 'b', 'datetime', 'date'], dtype='object')
# convert to numpy array
dfVal = df.values
# display datetime
print("dfVal[:,2]:", dfVal[:, 2])
dfVal[:,2]: [Timestamp('1999-12-31 23:59:12') Timestamp('1999-12-31 23:59:13')
Timestamp('1999-12-31 23:59:14')]
# try to convert
dfVal[:, 2].dt.date
Traceback (most recent call last):
File "/home/claudia/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2963, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-12-5cead683e881>", line 1, in <module>
dfVal[:, 2].dt.date
AttributeError: 'numpy.ndarray' object has no attribute 'dt'
答案 0 :(得分:2)
for (;;)
df
a b datetime
0 31.12.1999 23:59:12 4 1999-12-31 23:59:12
1 31.12.1999 23:59:13 5 1999-12-31 23:59:13
2 31.12.1999 23:59:14 6 1999-12-31 23:59:14
arr = df['datetime'].values
dt.date
arr.astype('datetime64[D]')
# array(['1999-12-31', '1999-12-31', '1999-12-31'], dtype='datetime64[D]')
dt.month
arr.astype('datetime64[M]') - arr.astype('datetime64[Y]') + 1
# array([12, 12, 12], dtype='timedelta64[M]')
dt.year
arr.astype('datetime64[Y]')
# array(['1999', '1999', '1999'], dtype='datetime64[Y]')
dt.date