尝试使用熊猫遍历每一行,评估该行的B列值是否包含A列中的任何值,然后填充对应于A列中每个值的新列C,D,E ...要获得相同的结果,下面的代码是我要做的,但是在这里,我需要事先知道行A中可能存在什么值。
d = {'country': ["USA", "China", "Singapore"], 'allies': ["Turkey, UK, France, India", "DPRK, Singapore", "USA, China"]}
df = pd.DataFrame(data=d)
df["USAally"] = df['allies'].map(lambda x: 1 if "USA" in x else 0)
df["Chinaally"] = df['allies'].map(lambda x: 1 if "China" in x else 0)
df["Singaporeally"] = df['allies'].map(lambda x: 1 if "Singapore" in x else 0)
答案 0 :(得分:2)
您可以在此处使用get_dummies
有效地做到这一点:
dummies = (df['allies'].str.get_dummies(sep=', ')
.reindex(df['country'].unique(), axis=1)
.add_suffix('_ally'))
df.join(dummies)
country allies USA_ally China_ally Singapore_ally
0 USA Turkey, UK, France, India 0 0 0
1 China DPRK, Singapore 0 0 1
2 Singapore USA, China 1 1 0
在哪里
dummies
USA_ally China_ally Singapore_ally
0 0 0 0
1 0 0 1
2 1 1 0
答案 1 :(得分:1)
让我们尝试一下,使用series.unique
来标识唯一的国家,然后使用str.contains
来检查是否存在。
for c in df.country.unique():
df[f'{c}_Aally'] = df.allies.str.contains(c).astype(int)
df
Out[20]:
country allies USA_Aally China_Aally Singapore_Aally
0 USA Turkey, UK, France, India 0 0 0
1 China DPRK, Singapore 0 0 1
2 Singapore USA, China 1 1 0
答案 2 :(得分:0)
这里是代码的一般化,首先获取letter
列中出现的所有唯一字母,然后逐个循环遍历它们,并基本上完成每个操作。< / p>
complete_letter_set = set(''.join(df['letter'])
for l in complete_letter_set:
df[f"letter{l}exists"] = df['letter'].map(lambda x: int(l in x))
请注意,我将条件1 if A in x else 0
简化为int(l in x)
,因为无论如何int(True) == 1
和int(False) == 0
。