NumPy 相当于 pandas 日期时间访问器操作

使用 Pandas,我可以通过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/user/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'


缥缈止盈
浏览 133回答 1
1回答

跃然一笑

df&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;a&nbsp; b&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; datetime0&nbsp; 31.12.1999 23:59:12&nbsp; 4 1999-12-31 23:59:121&nbsp; 31.12.1999 23:59:13&nbsp; 5 1999-12-31 23:59:132&nbsp; 31.12.1999 23:59:14&nbsp; 6 1999-12-31 23:59:14arr = df['datetime'].valuesdt.datearr.astype('datetime64[D]')# array(['1999-12-31', '1999-12-31', '1999-12-31'], dtype='datetime64[D]')dt.montharr.astype('datetime64[M]') - arr.astype('datetime64[Y]') + 1# array([12, 12, 12], dtype='timedelta64[M]')dt.yeararr.astype('datetime64[Y]')#&nbsp; array(['1999', '1999', '1999'], dtype='datetime64[Y]')dt.datearr.astype('datetime64[D]') - arr.astype('datetime64[M]') + 1# array([31, 31, 31], dtype='timedelta64[D]')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python