我想要计算子字符串列表在包含长字符串的列中出现的次数,并在pandas df中创建一个count列
Input:
ID History
1 USA|UK|IND|DEN|MAL|SWE|AUS
2 USA|UK|PAK|NOR
3 NOR|NZE
4 IND|PAK|NOR
lst=['USA','IND','DEN']
Output :
ID History Count
1 USA|UK|IND|DEN|MAL|SWE|AUS 3
2 USA|UK|PAK|NOR 1
3 NOR|NZE 0
4 IND|PAK|NOR 1发布于 2019-07-27 09:14:19
使用lambda:
df.History.apply(lambda x: len([i for i in x.split("|") if i in lst]))结果
0 3
1 1
2 0
3 1发布于 2019-07-27 08:40:09
以下是str.count的一种方法
df1.History.str.count('|'.join(lst))
Out[316]:
0 3
1 1
2 0
3 1
Name: History, dtype: int64
#df1['Count']= df1.History.str.count('|'.join(lst))https://stackoverflow.com/questions/57228301
复制相似问题