pandas to_dict python 本机日期时间类型而不是时间戳

pandas to_dict with python native datetime type and not timestamp

我有一个包含 Timesatamp 列的 pandas DataFrame df

我希望从 df 创建一个行迭代器(通过 iter.. 方法或通过 to_dict),其中 Timesatamp 值为 python datetime.

我试过这样做

for col in df.select_dtypes(['datetime']):
        df[col] = df[col].dt.to_pydatetime()

然而,使用上述迭代器方法时,列似乎仍然是 Timesatamp。 除了在迭代时手动转换每个值之外,是否有 'batch'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["d"]=df.d.apply(lambda t: t.date())                                                                              
df.d.to_dict()                                                                                                      

{0: datetime.date(2018, 1, 1), 1: datetime.date(2018, 1, 2)}

你可以试试

df[col] = pd.Series(df[col].dt.to_pydatetime(), dtype = object)

而不是

df[col] = df[col].dt.to_pydatetime()

有点相关,但如果您想将数据转储到 json,请将数据帧转换为 json

json_df = df.to_json(orient='records')

然后将数据输出到一个新的json文件

with open('out.json', 'w') as outfile:
    json.dump(json.loads(json_df), outfile)