我有一個 df 如下:
Policy Letter Password Lower Upper Count Lower_Minus_1 Upper_Minus_1
0 4-5 l rllllj 4 5 4 3 4
1 4-10 s ssskssphrlpscsxrfsr 4 10 8 3 9
2 14-18 p ppppppppppppppppppp 14 18 19 13 17
3 1-6 z zzlzvmqbzzclrz 1 6 6 0 5
4 4-5 j jhjjhxhjkxj 4 5 5 3 4
Lower_Minus_1 值將用作索引來搜索密碼中的該位置,以查看它是否與“字母”列中的字母匹配。
這條線有效:
print(df['Password'].str[3] == df['Letter'])
但是,它嚴格根據每一行的“密碼”中的值的第三個位置回傳 True\False。
前五名:
0 True
1 False
2 True
3 True
4 True
我不想要每一行的第三個位置。我想要每行的 Lower_Minus_1 位置。
我嘗試了以下方法,但都失敗了:
print(df['Password'].str[df['Letter']] == df['Letter'])
為每一行回傳 False,證明如下:
print((df['Password'].str[df['Letter']] == df['Letter']).sum())
回傳:0
然后我嘗試了這個:
print(df.apply(lambda x: x['Password'].str[x['Lower_Minus_1']], axis=1) == df['Letter'])
這會引發錯誤:
File "D:/AofC/2020_day2.py", line 56, in <lambda>
print(df.apply(lambda x: x['Password'].str[x['Lower_Minus_1']], axis=1) == df['Letter'])
AttributeError: 'str' object has no attribute 'str'
uj5u.com熱心網友回復:
df.apply(lambda x:x['Letter']== x['Password'][x.Lower_Minus_1], axis=1)
0 True
1 False
2 True
3 True
4 True
dtype: bool
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485532.html
標籤:python-3.x 熊猫 细绳
