gpt4 book ai didi

python - 为什么在 pandas 数据框列中应用更改 dtype

转载 作者:太空狗 更新时间:2023-10-30 01:06:49 24 4
gpt4 key购买 nike

我有以下数据框:

import pandas as pd
import numpy as np
df = pd.DataFrame(dict(A = np.arange(3),
B = np.random.randn(3),
C = ['foo','bar','bah'],
D = pd.Timestamp('20130101')))

print(df)

A B C D
0 0 -1.087180 foo 2013-01-01
1 1 -1.343424 bar 2013-01-01
2 2 -0.193371 bah 2013-01-01

dtypes 用于列:

print(df.dtypes)
A int32
B float64
C object
D datetime64[ns]
dtype: object

但是在使用apply之后他们都改变了对象:

print(df.apply(lambda x: x.dtype))
A object
B object
C object
D object
dtype: object

为什么 dtypes 被强制反对?我认为在 apply 中只应考虑列。

Pandas 0.17.1
python 3.4.3

最佳答案

您可以使用参数 reduce=False 和更多信息 here :

print (df.apply(lambda x: x.dtype, reduce=False))

A int32
B float64
C object
D datetime64[ns]
dtype: object

在较新版本的 pandas 中可以使用:

print (df.apply(lambda x: x.dtype, result_type='expand'))

关于python - 为什么在 pandas 数据框列中应用更改 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com