[英]compare two columns value in dataframe
我有一個像下面的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
如果值混合( 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.