python - Pandas:将一行 boolean 值附加到 df 使用 `loc` 更改为 `int`

标签 python pandas dataframe boolean

考虑 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/

相关文章:

c# - Python2.7 : Initialize constructor variable as byte array

python - 如何将图像添加到轴中的条形(matplotlib)

python - 如何在 Python 中检测 ftp 服务器超时

python:使用 scikit-learn 构建带权重的矩阵

python - 如何使用 Pandas 获取单元格的值并存储到变量中?

循环中的 R 动态数据框名称

javascript - 是否有可能在 Javascript 或 Python 中在 R 中实现类似 "non standard evaluation"的东西?

r - 从 R 中的数据框创建交叉表

python - 如何连接 Pandas 中包含列表(系列)的两列

python - 优先合并 2 列