python - 使用 pandas 中的 chunksize 参数提取每个值的基本计数

标签 python pandas count

我有一个包含以下类别的 CSV 文件:item1item2item3item4,其值正是以下之一:01234 >。 我想计算每个项目的每个值有多少个。 我的代码如下,df是相应的DataFrame:

outputDf = pandas.DataFrame()
cat_list = list(df.columns.values)
for col in cat_list:
        s = df.groupby(col).size()
        outputDf[col] = s

当我使用 read_csv 读取 CSV 时,我想使用 chunksize 参数执行完全相同的操作,因为我的 CSV 非常大。 我的问题是:我找不到找到 cat_list 的方法,也无法构建 outputDf

有人可以给我提示吗?

最佳答案

我会按列应用value_counts,而不是执行groupby:

>>> df = pd.read_csv("basic.csv", usecols=["item1", "item2", "item3", "item4"])
>>> df.apply(pd.value_counts)
   item1  item2  item3  item4
0     17     26     17     20
1     21     21     22     19
2     17     18     22     23
3     24     14     20     24
4     21     21     19     14

对于分块版本,我们只需要组装各个部分(确保fillna(0),这样如果一个部分没有 3,例如,我们会得到 0 和不是nan。)

>>> df_iter = pd.read_csv("basic.csv", usecols=["item1", "item2", "item3", "item4"], chunksize=10)
>>> sum(c.apply(pd.value_counts).fillna(0) for c in df_iter)
   item1  item2  item3  item4
0     17     26     17     20
1     21     21     22     19
2     17     18     22     23
3     24     14     20     24
4     21     21     19     14

(当然,在实践中,您可能希望使用尽可能大的 chunksize。)

关于python - 使用 pandas 中的 chunksize 参数提取每个值的基本计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25428661/

相关文章:

python - 如何在Python中完成套接字文件传输?

python - cv2.matchTemplate 在图像中发现错误的模板

python - 在 Pandas 中将索引连接到多重索引

python - 通过计算 python 中 groupby 之后的列中 0 出现的次数来获取子集

mysql - 统计首次通话后 6 天内重复通话的用户

MySQL将一个字段统计成两个不同的统计结果

python - sklearn标签编码器: TypeError : '<' not supported between instances of 'int' and 'str'

python - LZ 77、78 心电图压缩算法

python - Visual Studio 代码窗口,Python Pandas 。没有名为 pandas 的模块

facebook-graph-api - Facebook Graph API和FQL之类的依靠照片都不正确吗?