在 for 循环中使用三元条件添加新列
Add new column using ternary condition in for loop
如何编写这个三元条件,以便在我的数据框中有一个布尔列。
partenaire['topcodeclub'] = ''
for id, i in enumerate(partenaire.Adresse):
i = str(i)
r1 = re.findall(r"\d{5}",i)
'True' if (r1[0][:2]==partenaire.basecodeclub[id]) else 'False'
假设我有两列,我在每次迭代中都会比较它们。如果在我的 topcodeclub
中匹配它是 True 否则它是 False 如何在该列中添加 True
和 false
。
鉴于您的数据框看起来像这样:
Address basecodeclub
0 some false address 12345 12
1 whatever other address 67890 here 45
2 and more 34567 here 43
3 and even more 54321 then 54
您可以在 Address
列上使用 str.extract
并匹配 basecodeclub
:
>>> df['Address'].str.extract(r'(\d{5})')[0].str[:2] == df['basecodeclub']
0 True
1 False
2 False
3 True
dtype: bool
只需将这些值分配给 topcodeclub
:
>>> df['topcodeclub'] = df['Address'].str.extract(r'(\d{5})')[0].str[:2].eq(df['basecodeclub'])
Address basecodeclub topcodeclub
0 some false address 12345 12 True
1 whatever other address 67890 here 45 False
2 and more 34567 here 43 False
3 and even more 54321 then 54 True
在大多数情况下,几乎总有一种矢量化方法可以完成您在 pandas
中想要的内容。你应该尽可能避免循环帧。
如何编写这个三元条件,以便在我的数据框中有一个布尔列。
partenaire['topcodeclub'] = ''
for id, i in enumerate(partenaire.Adresse):
i = str(i)
r1 = re.findall(r"\d{5}",i)
'True' if (r1[0][:2]==partenaire.basecodeclub[id]) else 'False'
假设我有两列,我在每次迭代中都会比较它们。如果在我的 topcodeclub
中匹配它是 True 否则它是 False 如何在该列中添加 True
和 false
。
鉴于您的数据框看起来像这样:
Address basecodeclub
0 some false address 12345 12
1 whatever other address 67890 here 45
2 and more 34567 here 43
3 and even more 54321 then 54
您可以在 Address
列上使用 str.extract
并匹配 basecodeclub
:
>>> df['Address'].str.extract(r'(\d{5})')[0].str[:2] == df['basecodeclub']
0 True
1 False
2 False
3 True
dtype: bool
只需将这些值分配给 topcodeclub
:
>>> df['topcodeclub'] = df['Address'].str.extract(r'(\d{5})')[0].str[:2].eq(df['basecodeclub'])
Address basecodeclub topcodeclub
0 some false address 12345 12 True
1 whatever other address 67890 here 45 False
2 and more 34567 here 43 False
3 and even more 54321 then 54 True
在大多数情况下,几乎总有一种矢量化方法可以完成您在 pandas
中想要的内容。你应该尽可能避免循环帧。