简体   繁体   English

在将NaN添加到熊猫系列中时,是否保留布尔值和浮动值之间的区别?

[英]Preserving the distinctions between bools and floats when adding NaN to a pandas Series?

I am adding data to a pandas Series via the Series#append method. 我正在通过Series#append方法将数据添加到熊猫Series Unfortunately, when nan is added to a bool Series, it is automatically converted to a float Series. 不幸的是,将nan添加到bool系列时,它会自动转换为float系列。 Is there any way to avoid this conversion, or at least coerce it to object dtype, so as to preserve the distinction between bool s and float s? 有什么方法可以避免这种转换,或者至少将其强制转换为object dtype,以保持boolfloat之间的区别?

>>> Series([True])                            
0    True
dtype: bool
>>> Series([True]).append(Series([np.nan]))
0     1
0   NaN
dtype: float64

As @Jeff said, the best way is going to be to append a Series with object dtype 就像@Jeff所说的,最好的方法是将一个带有object dtypeSeries附加到

Here's an example using Series 这是使用Series的示例

s = Series([True])
s.append(Series([nan], index=[1], dtype=object))

yielding 生产

0    True
1     NaN
dtype: object

And one with a DataFrame : 还有一个带有DataFrame

df = DataFrame({'a': rand(10) > 0.5, 'b': randn(10)}, columns=list('ab'))
df2 = DataFrame({'a': Series([nan], dtype=object), 'b': [1.0]}, columns=df.columns, index=[len(df)])
df3 = df.append(df2)
print df3
print
print df3.dtypes

which gives 这使

        a      b
0   False -0.865
1    True -0.186
2    True  0.078
3    True  0.995
4   False -1.420
5    True -0.340
6    True  0.042
7    True -0.627
8    True -0.217
9    True  1.226
10    NaN  1.000

a     object
b    float64
dtype: object

It's a bit clunky looking, but if you've already got the Series then you can do s.astype(object) to convert them to object dtype before appending. 这是一个有点笨拙的寻找,但如果你已经拿到了Series那么你可以做s.astype(object)将它们转换为object dtype附加之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM