【问题标题】:How to combine the rows in data frame?如何组合数据框中的行?
【发布时间】:2016-10-27 06:05:36
【问题描述】:

真的很烦人,我找不到通过找到平均值或标准偏差或其他东西来组合多行或多列的方法。有人可以给我一个想法吗?谢谢!

【问题讨论】:

    标签: python python-2.7 python-3.x pandas dataframe


    【解决方案1】:

    我认为您可以将groupby index 地板除以10 并聚合meanstd

    np.random.seed(1)
    df = pd.DataFrame(np.random.randint(10, size=(5,5)),index=[1971,1972,1981,1982,1991])
    print (df)
          0  1  2  3  4
    1971  5  8  9  5  0
    1972  0  1  7  6  9
    1981  2  4  5  2  4
    1982  2  4  7  7  9
    1991  1  7  0  6  9
    
    print (df.index // 10)
    Int64Index([197, 197, 198, 198, 199], dtype='int64')
    
    df1 = df.groupby([df.index // 10]).mean()
    df1.index = df1.index.astype(str) + '0s' 
    print (df1)
             0    1    2    3    4
    1970s  2.5  4.5  8.0  5.5  4.5
    1980s  2.0  4.0  6.0  4.5  6.5
    1990s  1.0  7.0  0.0  6.0  9.0
    

    df1 = df.groupby([df.index // 10]).std()
    df1.index = df1.index.astype(str) + '0s' 
    print (df1)
                  0         1         2         3         4
    1970s  3.535534  4.949747  1.414214  0.707107  6.363961
    1980s  0.000000  0.000000  1.414214  3.535534  3.535534
    1990s       NaN       NaN       NaN       NaN       NaN
    

    【讨论】:

    • 如果我的回答有帮助,别忘了accept。您也可以投票 - 单击接受标记上方1 上方的小三角形。谢谢。
    • 谢谢。也许是个小建议——我认为您可以将文本用作图片,因为回答者无法复制数据。您也可以查看非常好的答案 - How to make good reproducible pandas examples。美好的一天,祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多