考虑 df
:
In [2098]: df = pd.DataFrame({'a': [1,2], 'b':[3,4]})
In [2099]: df
Out[2099]:
a b
0 1 3
1 2 4
现在,我尝试附加一个 list
值到 df
:In [2102]: df.loc[2] = [3, 4]
In [2103]: df
Out[2103]:
a b
0 1 3
1 2 4
2 3 4
到目前为止一切都很好。但是现在当我尝试添加带有 boolean 值列表的行时,它会将其转换为
int
:In [2104]: df.loc[3] = [True, False]
In [2105]: df
Out[2105]:
a b
0 1 3
1 2 4
2 3 4
3 1 0
我知道我可以转换我的 df
进入 str
然后可以附加 boolean 值,例如:In [2131]: df = df.astype(str)
In [2133]: df.loc[3] = [True, False]
In [2134]: df
Out[2134]:
a b
0 1 3
1 2 4
3 True False
但是,我想知道这种行为背后的原因。为什么不自动更改dtypes
列到 object
当我追加 boolean
要吗?我的 Pandas 版本是:
In [2150]: pd.__version__
Out[2150]: '1.1.0'
最佳答案
当我将 boolean 值附加到它时,为什么它不会自动将列的 dtypes 更改为对象?
因为类型正在向上转换(请参阅 upcasting ),来自文档:
Types can potentially be upcasted when combined with other types, meaning they are promoted from the current type (e.g. int to float).
Upcasting 根据 numpy 规则工作:
Upcasting is always according to the numpy rules. If two different dtypes are involved in an operation, then the more general one will be used as the result of the operation.
要了解如何应用 numpy 规则,您可以使用函数 find_common_type , 如下:
res = np.find_common_type([bool, np.bool], [np.int32, np.int64])
print(res)
输出 int64
关于python - Pandas:将一行 boolean 值附加到 df 使用 `loc` 更改为 `int`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65420853/