我不知道何时在Series(或数据框)上替换0,是否还会替换False?

时间:2018-09-01 13:08:03

标签: python pandas

我想知道是否要替换数据帧中的所有整数0False也会被替换吗?我已经在MacBook上尝试过了,但它没有被替换,但是我的一位朋友说他被替换了。我想知道这取决于您使用什么机器?

1 个答案:

答案 0 :(得分:0)

是否将替换False取决于系列的dtype:

In [12]: pd.Series([0, 1]).replace(0, 99)
Out[12]: 
0    99
1     1
dtype: int64

In [13]: pd.Series([0.0, 1.0]).replace(0, 99)
Out[13]: 
0    99.0
1     1.0
dtype: float64

In [14]: pd.Series([False, True]).replace(0, 99)
Out[14]: 
0    False
1     True
dtype: bool

In [15]: pd.Series([0, 0.0, False, 1.0]).replace(0, 99)
Out[15]: 
0    99.0
1    99.0
2    99.0
3     1.0
dtype: float64

如果不替换它,您的系列可能有dtype = bool,因此pandas已决定注意类型的不同。如果您的系列具有dtype = object,则将其视为Python级别对象的集合(基本上是它的集合),并且由于False == 0 == 0.0,因此将全部三个替换。