我有一個看起來像這樣的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() 檢查每一行的不同值。
uj5u.com熱心網友回復:
您可以在每一行上應用自定義函式(如回圈):
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://www.uj5u.com/houduan/485536.html
標籤:python-3.x 熊猫 数数