Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pandas Dataframe-在字符串中查找字符串的匹配项_Python_Pandas - Fatal编程技术网

Python Pandas Dataframe-在字符串中查找字符串的匹配项

Python Pandas Dataframe-在字符串中查找字符串的匹配项,python,pandas,Python,Pandas,我有一个数据帧,看起来像这样(但更长): 如何计算密码中字母的出现次数?第一行为6,第二行为4 这不起作用,因为count需要正则表达式: df['accounts']=df['Password'].str.count(df['Letter']).astype(int) 那我怎么做呢?你可以做: df['Occurrences'] = [pas.count(letter) for pas, letter in zip(df['Password'], df['Letter'])] print(df

我有一个数据帧,看起来像这样(但更长):

如何计算密码中字母的出现次数?第一行为6,第二行为4

这不起作用,因为count需要正则表达式:

df['accounts']=df['Password'].str.count(df['Letter']).astype(int)

那我怎么做呢?

你可以做:

df['Occurrences'] = [pas.count(letter) for pas, letter in zip(df['Password'], df['Letter'])]
print(df)
输出

  Letter              Password  Occurrences
0      l  klfbblslvjclmlnqklvg            6
1      h        pghjchdxhnjhjd            4

在这种情况下,您可以使用
apply

df['Occurrences'] = df.apply(lambda x: x['Password'].count(x['Letter']), axis=1)
输出:

  Letter              Password  Occurrences
0      l  klfbblslvjclmlnqklvg            6
1      h        pghjchdxhnjhjd            4

@DaniMesejo缩短了代码库,以换取少量的额外时间,特别是当您的数据帧名称是
长的东西时。有些人可能认为它更可读,但我可以看到一些人更喜欢列表理解。谢谢你的回答!谢谢,这很有效。我一定会得到更多的应用功能在未来的使用!谢谢,这也行!但只能接受一个答案:-(
  Letter              Password  Occurrences
0      l  klfbblslvjclmlnqklvg            6
1      h        pghjchdxhnjhjd            4