首页 > 解决方案 > 列中的计数列表 - Pandas

问题描述

Pytoneers 或 Pythonistas 同胞,

我希望我能在这个问题上得到你的帮助:

我有多个熊猫数据框,其中包含如下示例:

在此处输入图像描述

我想创建一个函数来计算列表中的值,例如 [a,b,c] 并遍历列和数据框。我想返回列表中列中找到的项目总数。我写了这段代码,但它似乎没有奏效。能否请你帮忙?预先感谢您的回答。PS:因为我是新手,所以我的业力很低:D

list_of_dataframes = [k,p,r]

list_of_chars = ["a","b","c"]

for dataframe in list_of_dataframes:
        for values in list_of_chars:
            for columns in dataframe:
                count = 0
                if dataframe.columns.str.contains(list_of_chars):
                    dataframe['Total']=count+1
                else dataframe['Total']

标签: pythonpandasstringdataframe

解决方案


将字符串列连接在一起,然后Series.str.count用连接的值一起计算值,并用空字符串替换缺失值。因为有一些带有正则表达式字符的列表值,所以必须re.escape先将它们转义:

在您的解决方案中:

k = pd.DataFrame({'ID':[1,2, 3], 
                   'String1':['a d d','a','s'],
                   'String2':['a','a b b','c']})
 
p = pd.DataFrame({'ID':[1,2, 3], 
                   'String1':['c','b','c'],
                   'String2':['a b','a c','d a']})
 
r = pd.DataFrame({'ID':[1,2, 3], 
                   'String1':['a','c d as','c a d'],
                   'String2':['a b c c','a b c','d a b f']})
 
list_of_dataframes = [k,p,r]

import re

list_of_chars = ["a","b","c"]
pat = '|'.join(['({})'.format(re.escape(c)) for c in list_of_chars])

for i, dataframe in enumerate(list_of_dataframes):
    dataframe['Total'] = dataframe.select_dtypes(object).fillna('').agg(''.join, 1).str.count(pat)
    list_of_dataframes[i] = dataframe
     
print (list_of_dataframes)
[   ID String1 String2  Total
0   1   a d d       a      2
1   2       a   a b b      4
2   3       s       c      1,    ID String1 String2  Total
0   1       c     a b      3
1   2       b     a c      3
2   3       c     d a      2,    ID String1  String2  Total
0   1       a  a b c c      5
1   2  c d as    a b c      5
2   3   c a d  d a b f      4]

推荐阅读