我有一个如下所示的df:
Policy Letter Password Lower Upper
0 4-5 l rllllj 4 5
1 4-10 s ssskssphrlpscsxrfsr 4 10
2 14-18 p ppppppppppppppppppp 14 18
3 1-6 z zzlzvmqbzzclrz 1 6
4 4-5 j jhjjhxhjkxj 4 5
我希望计算“信函”列中的字母在密码中出现的次数,以及“密码”列中每一行出现的次数。
换句话说,第一行(4)的密码中有多少个l。第二行(8)的密码中有多少s。
诸若此类。
如果我这么做:
df['Count'] = df['Password'].str.count('s')
它正确运行,但它只计算列中的每个密码中的s。
当我尝试这个:
df['Count'] = df['Password'].str.count(df['Letter'])
它抛出一个错误:
TypeError: 'Series' objects are mutable, thus they cannot be hashed
我不知道如何(如果可能的话)让str.count()检查每个行的不同值。
发布于 2022-06-01 21:41:58
您可以在每一行上应用自定义函数(如循环):
df['Count'] = df.apply(lambda x: x['Password'].count(x['Letter']), axis=1)
print(df)
# Output
Policy Letter Password Lower Upper Count
0 4-5 l rllllj 4 5 4
1 4-10 s ssskssphrlpscsxrfsr 4 10 8
2 14-18 p ppppppppppppppppppp 14 18 19
3 1-6 z zzlzvmqbzzclrz 1 6 6
4 4-5 j jhjjhxhjkxj 4 5 5
具有理解力:
df['Count'] = [x.Password.count(x.Letter) for x in df.itertuples()]
# df['Count'] = [x[3].count(x[2]) for x in df.itertuples()]
https://stackoverflow.com/questions/72468312
复制相似问题