为了账号安全,请及时绑定邮箱和手机立即绑定

如何根据值的频率拆分 pandas 数据框

如何根据值的频率拆分 pandas 数据框

芜湖不芜 2024-01-27 15:19:56
我有兴趣根据 B 列中条目的频率将该数据帧分成 20 个较小的数据帧。B 具有数字条目,其中一些条目重复多次,如下所示。 A (index)              B (Column of interest)     0                              1    1                              2    2                              2    3                              2      4                              3   ...                            ...   25643                          5238  25644                          5238   25645                          5238  25646                          5238  25647                          5238我希望每个频率都有一个数据框:1-10、11-20、21-30、....、191-200。意思是,1-10 数据帧包含 B 中在该数据帧中出现 1 到 10 次的所有条目。同样,11-20 数据帧包含在整个数据帧中出现 11 次和 20 次的所有条目。最后,我应该有 20 个数据帧,所有这些数据帧都分割了这个主数据帧。我所能做的就是使用以下代码从 B 列中找到与这些 freeuqncies 相对应的所需条目中的不同数量的条目:   df.loc[(df['B'] > 0) & (df['B'] < 11)]   df.loc[(df['B'] > 10) & (df['B'] < 21)]                    ...   df.loc[df['B'] > 190) & (df['B'] < 201)   我一直在考虑使用该groupby()函数,但是,我还没有找到一种根据频率对列条目进行分组的方法。任何帮助表示赞赏!
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

  • 计算数据帧中每个值的出现次数,将频率范围以 10 为一组进行分组,然后为每个范围创建dict一个DataFrames

    • 垃圾箱标签将成为dict钥匙

    • bins列是分类的,因此.groupby将为每个标签创建一个组,即使该组为空,因此使用pandas.DataFrame.empty,因此只有非空组才会添加到dictof 中DataFrames

    • 替换g: dfg为中g: pd.DataFrame(dfg.B)只有列。 Bdict

    • 使用dfg.reset_index(drop=True)pd.DataFrame(dfg.B).reset_index(drop=True)删除原始索引。

    • labels使用,因为它们更容易用作dict密钥

    • 如果不使用labelsdict键将是Interval, 就像[Interval(10, 20, closed='right'),这很麻烦。

    • df.B.map(df.groupby('B')['B'].count())也有效,但不是必需的。

  1. 使用pandas.Series.value_counts()pandas.Series.map在 中创建一个计数列df,它将传达列中值的频率B

  2. 用于pd.cut对频率范围进行分类

  3. pandas.DataFrame.groupby与 a 一起使用可根据 bin 标签 dict-comprehension创建dictof 。DataFrames

import pandas as pd

import numpy as np


# setup test dataframe

np.random.seed(365)

df = pd.DataFrame({'B': np.random.randint(5238, size=(200000))})


# add a counts column to the dataframe

df['counts'] = df.B.map(df.B.value_counts())


# create a bins column for the frequency range

bins = range(0, 201, 10)

labels = range(10, 201, 10)

df['bins'] = pd.cut(df.counts, bins=bins, right=True, labels=labels)


# display(df.head())

      B  counts bins

0  2740      37   40

1  4897      41   50

2  4955      45   50

3   428      31   40

4   226      34   40


# create a dict of dataframes for the non-empty bins

dfd = {g: dfg for g, dfg in df.groupby('bins') if not dfg.empty}


# print dict keys

dfd.keys()

[out]:

dict_keys([20, 30, 40, 50, 60, 70])


# display(dfd[20].head())

          B  counts bins

5350   4986      19   20

5646   4952      20   20

11232  3728      19   20

11707  2819      20   20

13547  3728      19   20


查看完整回答
反对 回复 2024-01-27
  • 1 回答
  • 0 关注
  • 17 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信