python - 列中的计数列表 - 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']
解决方案
将字符串列连接在一起,然后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]
推荐阅读
- python - 为什么使用数组作为索引会改变多维 ndarray 的形状?
- sql - 按 -SQL ORACLE 分组
- javascript - 如何通过路由打开 ionic 4 modal?
- python - 并行处理 Airflow 上的百万个文件列表
- ruby-on-rails - Rails:在视图中显示按日期排序的两个查询的组合
- java - 从firebase检索数据到arraylist
- java - java中如何与另一个进程通信?
- sql - 如何在 t-sql 上的联合子句上获得更好的性能
- spring-security - 如何使用自定义 Spring Boot 登录表单调用控制器发布方法
- android - 如何将字符串数组列表从适配器发送到它自己的活动