我有一个 pandas
DataFrame
df
包含 Timesatamp
列。
我希望从 iter..
创建一个行迭代器(通过 to_dict
方法或通过 df
)哪里Timesatamp
值是 python datetime
.
我试过这样做
for col in df.select_dtypes(['datetime']):
df[col] = df[col].dt.to_pydatetime()
但是似乎列仍然是
Timesatamp
当使用上述迭代器方法时。有没有 '批量'y 除了在迭代时手动转换每个值之外,如何实现这一点?
示例
df = pd.DataFrame({'d': pd.date_range('2018-01-01', freq='12h', periods=2), 'a':[1,2]})
for col in df.select_dtypes(['datetime']):
df[col] = df[col].dt.to_pydatetime()
print(df.to_dict('records'))
输出:
[{'d': Timestamp('2018-01-01 00:00:00'), 'a': 1}, {'d': Timestamp('2018-01-01 12:00:00'), 'a': 2}]
所需的输出:
[{'d': datetime.datetime(2018, 1, 1, 0, 0), 'a': 1}, {'d': datetime.datetime(2018, 1, 1, 12, 0), 'a': 2}]
最佳答案
你可以试试
df[col] = pd.Series(df[col].dt.to_pydatetime(), dtype = object)
代替
df[col] = df[col].dt.to_pydatetime()
关于python - 带有python native 日期时间类型而不是时间戳的pandas to_dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59016693/