我有一个数据框架,其中两个列的字符串是逗号分隔的。
我试图用速度高效的方法来计算三维列,以指示是否有从列A中分离的字符串出现在B列中。
例如:
df = pd.DataFrame({'A':['apple', 'cucamber', 'tomato,mellon', 'tomato,potato'],
'B':['apple,banana', 'pineapple', 'tomato juice', 'cheese,tomato,onion']})结果应该是
A B C
apple apple,banana 1
cucamber pineapple 0
tomato,mellon tomato juice 0
tomato,potato cheese,tomato,onion 1可能是>1百万行。
如果它对速度至关重要,即使没有分割第二列也可以,只需在第二列中搜索从第一列中分离出来的字符串。
A B C
apple apple,banana 1
cucamber pineapple 0
tomato,mellon tomato juice 1
tomato,potato cheese,tomato,onion 1感谢你的帮助。
发布于 2021-06-29 09:54:45
如果匹配至少一个字符串的话,有一个与lsit理解和any相匹配的想法:
df['C'] = [any(z in y for z in x.split(',')) for x, y in df[['A','B']].to_numpy()]
df['C'] = df['C'].astype(int)
print (df)
A B C
0 apple apple,banana 1
1 cucamber pineapple 0
2 tomato,mellon tomato juice 1
3 tomato,potato cheese,tomato,onion 1编辑:
使用缺失值的一种可能的解决方案是先替换它们,如果不需要匹配它们,则用不同的值替换每个列的NaN,如下所示:
df = pd.DataFrame({'A':[None, 'cucamber', 'tomato,mellon', 'tomato,potato'],
'B':['apple,banana', None, 'tomato juice', 'cheese,tomato,onion']})
d = {'A':'missing1', 'B':'missing'}
df['C'] = [any(z in y for z in x.split(',')) for x, y in df[['A','B']].fillna(d).to_numpy()]
df['C'] = df['C'].astype(int)
print (df)
A B C
0 None apple,banana 0
1 cucamber None 0
2 tomato,mellon tomato juice 1
3 tomato,potato cheese,tomato,onion 1https://stackoverflow.com/questions/68176249
复制相似问题