python - 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'
解决方案
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
arr.astype('datetime64[D]') - arr.astype('datetime64[M]') + 1
# array([31, 31, 31], dtype='timedelta64[D]')
推荐阅读
- php - 无法从 Contact Form 7 Form 在 Wordpress 之外发送 POST 值
- c# - 如何让我的 WPF 文本框在变量中插入值并将其显示在文本区域中?
- python - 从 Cloud Functions 写入 Pub/Sub
- sql - SQL - 使用几个条件从数据库中检索记录
- php - 将 Ajax 请求结果保存在文件中
- ruby-on-rails - 如何将此 Ruby on Rails 代码更改为 Laravel?
- excel - 选择过滤结果
- r - 如何将给定数据框的子集分成 3 个组,每个组在 R 中包含 5 行
- python - 比较数据框日期列并返回新列
- php - 具有多个表重复信息的PHP INNER JOIN sql查询