gpt4 book ai didi

python - 获取支持 NA/可为空的 boolean pandas 列

转载 作者:太空狗 更新时间:2023-10-30 00:02:12 25 4
gpt4 key购买 nike

如何创建一个 dtype bool(或 int 类型)并支持 Nan/缺失值的 pandas dataframe 列?

当我这样尝试时:

d = {'one' : np.ma.MaskedArray([True, False, True, True], mask = [0,0,1,0]),
'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print (df.dtypes)
print (df)

one 隐式转换为对象。 ints 也类似:

d = {'one' : np.ma.MaskedArray([1,3,2,1], mask = [0,0,1,0]),
'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print (df.dtypes)
print (df)

one 在这里隐式转换为 float64,我更愿意留在 int 域中而不处理浮点运算它的特质(比较时总是有容忍度,舍入误差等)

最佳答案

Pandas >= 1.0

截至 pandas 1.0.0(2020 年 1 月),有 experimental support for nullable booleans直接:

In [183]: df.one.astype('boolean')
Out[183]:
a True
b False
c <NA>
d True
Name: one, dtype: object

在此版本中,pandas 还将在整数情况下使用 pd.NA 而不是 np.nan:

In [166]: df.astype('Int64')
Out[166]:
one two
a 1 1
b 3 2
c <NA> 3
d 1 4

Pandas >= 0.24

在整数情况下,从 pandas 0.24(2019 年 1 月)开始,您可以使用 nullable integers实现你想要的:

In [165]: df
Out[165]:
one two
a 1.0 1.0
b 3.0 2.0
c NaN 3.0
d 1.0 4.0

In [166]: df.astype('Int64')
Out[166]:
one two
a 1 1
b 3 2
c NaN 3
d 1 4

这通过将支持数组转换为 arrays.IntegerArray 来实现, boolean 值没有等效的东西,但在 this GitHub issue 中讨论了这方面的一些工作。和 this PyData talk .你可以自己写 extension type也涵盖这种情况,但如果您可以接受由整数 0 和 1 表示的 boolean 值,则一种方法可能如下:

In [183]: df.one
Out[183]:
a True
b False
c NaN
d True
Name: one, dtype: object

In [184]: (df.one * 1).astype('Int64')
Out[184]:
a 1
b 0
c NaN
d 1
Name: one, dtype: Int64

关于python - 获取支持 NA/可为空的 boolean pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34520267/

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