【问题标题】:I want to group Columns in pandas [closed]我想在熊猫中对列进行分组[关闭]
【发布时间】:2019-04-04 20:49:09
【问题描述】:

我有包含不同列的数据框,我想在 AccountID 的基础上对列进行分组

和预期的输出看起来像这样

【问题讨论】:

  • 到目前为止您尝试过什么?从documentation 开始然后从那里开始怎么样?
  • 我阅读了文档,但文档中的可用方法(groupby)只返回了三列
  • 在这种情况下,请出示您的代码
  • c=differenc.groupby(['AccountID']).mean()
  • 你只得到三列的原因(我猜是因为我看不到你的数据)是因为只有这 3 列是数字,而.mean() 不能对非数字列进行操作

标签: python pandas dataframe group-by


【解决方案1】:

试试这个:

uniq_accounts = differenc['AccountID'].unique()
grped = differenc.groupby('AccountID')

## You can get the grouped data for a certain AccountId like this and store in a dictionary:

d = {}
for account in uniq_accounts:
    d[account] = grped.get_group(account)

##Now, dictionary has all accounts data in separate dataframes. You can access like this:

for key in d.keys():
    print(d[key])

## If you want to fetch data for a particular AccountID(lets say 316001718201), you can do:

print(d['316001718201'])

如果有帮助,请告诉我。

【讨论】:

    【解决方案2】:

    这应该可以通过 DataFrame 的 groupby 函数实现,在这种情况下可能是 differenc.groupby('AccountID')

    【讨论】:

    • 我已经尝试过了,但这只给出了三列并忽略了剩余的列
    • 这很奇怪,你能把你的代码给我看一下吗?
    • c=differenc.groupby(['AccountID']).mean()
    • 你看到的三列是;第一级组,第二级组和计算的平均值。请看这个pandas.pydata.org/pandas-docs/stable/groupby.html
    猜你喜欢
    • 1970-01-01
    • 2020-08-10
    • 2022-12-12
    • 1970-01-01
    • 2021-07-20
    • 2018-10-12
    • 1970-01-01
    • 2018-04-20
    • 2016-02-02
    相关资源
    最近更新 更多