pandas中size方法,使用pandas中的chunksize参数提取每个值的基本计数

I have a CSV file with the following categories: item1,item2,item3,item4 which values is exactly one of the following: 0,1,2,3,4.

I would like to count for each items how many are there for each value.

My code is the following, df being the corresponding DataFrame:

outputDf = pandas.DataFrame()

cat_list = list(df.columns.values)

for col in cat_list:

s = df.groupby(col).size()

outputDf[col] = s

I would like to do exactly the same using the chunksize parameter when I read my CSV with read_csv, because my CSV is very big.

My problem is: I can't find a way to find the cat_list, neither to build the outputDf.

Can someone give me a hint?

解决方案

I'd apply value_counts columnwise rather than doing 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

And for the chunked version, we just need to assemble the parts (making sure to fillna(0) so that if a part doesn't have a 3, for example, we get 0 and not 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

(Of course, in practice you'd probably want to use as large a chunksize as you can get away with.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值