【发布时间】:2016-11-08 05:58:43
【问题描述】:
我有一个如下的csv数据框,我想比较两列值并生成第三列,如果值相同将返回True,不一样返回False,如何与pandas python比较?
one two
1 a
2 b
3 a
4 b
5 5
6 6
7 7
8 8
9 9
10 10
【问题讨论】:
标签: python pandas compare multiple-columns
我有一个如下的csv数据框,我想比较两列值并生成第三列,如果值相同将返回True,不一样返回False,如何与pandas python比较?
one two
1 a
2 b
3 a
4 b
5 5
6 6
7 7
8 8
9 9
10 10
【问题讨论】:
标签: python pandas compare multiple-columns
如果值混合(string 和 int),则需要:
df['three'] = df.one == df.two
但是如果值没有混合,则需要to_numeric - 第一列的dtype 是int,第二列是object,显然string 和列中的one 不是NaN 值,因为to_numeric 带参数errors='coerce' 返回NaN 对于非数值:
print (pd.to_numeric(df.two, errors='coerce'))
0 NaN
1 NaN
2 NaN
3 NaN
4 5.0
5 6.0
6 7.0
7 8.0
8 9.0
9 10.0
Name: two, dtype: float64
df['three'] = df.one == pd.to_numeric(df.two, errors='coerce')
print (df)
one two three
0 1 a False
1 2 b False
2 3 a False
3 4 b False
4 5 5 True
5 6 6 True
6 7 7 True
7 8 8 True
8 9 9 True
9 10 10 True
Series.eq 的更快解决方案:
df['three'] = df.one.eq(pd.to_numeric(df.two, errors='coerce'))
print (df)
one two three
0 1 a False
1 2 b False
2 3 a False
3 4 b False
4 5 5 True
5 6 6 True
6 7 7 True
7 8 8 True
8 9 9 True
9 10 10 True
【讨论】: