Pandas的一种类型没有像预期的那样工作(无声地严重失败)

k97glaaz  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(128)

我遇到过panda.astype()的这种奇怪行为(我使用的是1.5.2版本)。当试图将列转换为整数,然后请求dtype时,一切似乎都很好。直到你试图按行提取值时,你会得到不一致的类型。
编码:

import pandas as pd
import numpy as np
​
df = pd.DataFrame(np.random.randn(3, 3))
df.loc[:, 0] = df.loc[:, 0].astype(int)
​
print(df)
print(df.dtypes)
print(df.iloc[0, :])
print(type(df.values[0, 0]))

输出:

0         1         2
0  0 -0.232432  1.025643
1 -1  0.556968 -0.729378
2 -1  1.285546 -0.541676
0      int64
1    float64
2    float64
dtype: object
0    0.000000
1   -0.232432
2    1.025643
Name: 0, dtype: float64
<class 'numpy.float64'>

你猜我哪里做错了?
尝试在没有loc的情况下调用

df[0] = df[0].astype(int)

也不行

e0bqpujr

e0bqpujr1#

我认为这是由于使用了df.values,因为它将尝试返回一个Numpy representation of the DataFrame
默认情况下,返回数组的dtype将是DataFrame中所有类型的公共NumPy dtype

>>> from pandas.core.dtypes.cast import find_common_type
>>> find_common_type(df.dtypes.to_list()) # df is your dataframe
dtype('float64')

相关问题