【问题标题】:Find mean of the grouped rows of pandas dataframe查找熊猫数据框分组行的平均值
【发布时间】:2016-03-03 20:42:35
【问题描述】:

我处于非常基本的 Python 水平。我在这里遇到一个问题,有人可以帮我吗? 我有一个大熊猫数据框,我想查找行并确实意味着,如果每行的第一列具有一些相似的值(例如:某个整数由 '_' 另一个整数分隔)。

我尝试使用 .split 来匹配列表的第一个编号,它适用于单行,但如果我对行进行迭代,则会引发错误。 我的数据框看起来像:

d = {'ID' : pd.Series(['1_1', '2_1', '1_2', '2_2' ], index=['0','1','2', '3']),
     'one' : pd.Series([2.5, 2, 3.5, 2.5], index=['0','1', '2', '3']),
     'two' : pd.Series([1, 2, 3, 4], index=['0', '1', '2', '3'])}
df2 = pd.DataFrame(d)

要求:

拆分后在第一个位置具有相似 ID 的行的平均值。前任。 1_1 和 1_2、2_1 和 2_2 的平均值

输出:

 ID  one  two
0  1  3    2
1  2  2.25 3

这是我的代码, 工作版本:((df2.ix[0,0]).split('_'))[0]

错误版本:

 for i in df2.iterrows():
                   df2[df2.columns[((df2.ix[0,0]).split('_'))[0] == ((df2.ix[0,0]).split('_'))[0]]]

期待早日回复.. 提前谢谢..

【问题讨论】:

  • 您能否发布原始输入数据、重现您的 df 的代码以及您想要的输出 df 的样子以避免任何歧义
  • 进入你的问题而不是作为评论,因为格式在 cmets 中丢失了
  • 你能发布想要的输出df是什么样的吗,谢谢

标签: python pandas rows mean


【解决方案1】:

您可以使用 [strmethods](http://pandas.pydata.org/pandas-docs/stable/text.html#splitting-and-replacing-strings) and then usegroupby` 方法仅使用 ID 列的第一个数字创建新列:

df['groupedID'] = df.ID.str.split('_').str.get(0)

In [347]: df
Out[347]:
     ID  one  two groupedID
0  10_1  2.5    1        10
1   2_1  2.0    2         2
2  10_2  3.5    3        10
3   2_2  2.5    4         2

df1 = df.groupby('groupedID').mean()

In [349]: df1
Out[349]:
            one  two
groupedID
10         3.00    2
2          2.25    3

如果您需要将索引名称改回“ID”:

df1.index.name = 'ID'

In [351]: df1
Out[351]:
     one  two
ID
10   3.00    2
2   2.25    3

【讨论】:

  • 这个很好,但是如果 ID 包含 143_1 并且我需要 143 作为 ID 怎么办?
猜你喜欢
  • 2018-02-01
  • 2021-03-10
  • 1970-01-01
  • 2020-04-26
  • 2018-05-15
  • 2019-04-16
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
相关资源
最近更新 更多