簡體   English   中英

Python:如何將.mean的特定列添加到數據幀

[英]Python: How to add specific columns of .mean to dataframe

如何將b和c的方法添加到我的數據框中? 我試過合並,但它似乎沒有用。 所以我想要兩個額外的列b_mean和c_mean添加到我的數據幀中,結果為df.groupBy('date').mean()

數據幀

  a  b  c  date
0  2  3  5     1
1  5  9  1     1
2  3  7  1     1

我有以下代碼

import pandas as pd

a = [{'date': 1,'a':2, 'b':3, 'c':5}, {'date':1, 'a':5, 'b':9, 'c':1}, {'date':1, 'a':3, 'b':7, 'c':1}]

df = pd.DataFrame(a)

x =  df.groupby('date').mean()

編輯:

期望的輸出將是以下df.groupby('date').mean()返回:

             a         b         c
date                              
1     3.333333  6.333333  2.333333

我想要的結果將是以下數據框架

   a  b  c  date  a_mean   b_mean
0  2  3  5     1  3.3333   6.3333
1  5  9  1     1  3.3333   6.3333 
2  3  7  1     1  3.3333   6.3333

正如@ayhan所提到的,你可以使用pd.groupby.transform() 變換類似於apply,但它使用與原始數據幀相同的索引,而不是分組的列中的唯一值。

df['a_mean'] = df.groupby('date')['a'].transform('mean')
df['b_mean'] = df.groupby('date')['b'].transform('mean')

>>> df
   a  b  c  date    b_mean    a_mean
0  2  3  5     1  6.333333  3.333333
1  5  9  1     1  6.333333  3.333333
2  3  7  1     1  6.333333  3.333333


使用joinrsuffix參數。

df.join(df.groupby('date').mean(), on='date', rsuffix='_mean')

   a  b  c  date    a_mean    b_mean    c_mean
0  2  3  5     1  3.333333  6.333333  2.333333
1  5  9  1     1  3.333333  6.333333  2.333333
2  3  7  1     1  3.333333  6.333333  2.333333

我們可以將它限制為['a', 'b']

df.join(df.groupby('date')[['a', 'b']].mean(), on='date', rsuffix='_mean')

   a  b  c  date    a_mean    b_mean
0  2  3  5     1  3.333333  6.333333
1  5  9  1     1  3.333333  6.333333
2  3  7  1     1  3.333333  6.333333

額外的功勞
沒有真正回答你的問題...但我覺得它很整潔!

d1 = df.set_index('date', append=True).swaplevel(0, 1)
g = df.groupby('date').describe()
d1.append(g).sort_index()

                   a         b         c
date                                    
1    0      2.000000  3.000000  5.000000
     1      5.000000  9.000000  1.000000
     2      3.000000  7.000000  1.000000
     25%    2.500000  5.000000  1.000000
     50%    3.000000  7.000000  1.000000
     75%    4.000000  8.000000  3.000000
     count  3.000000  3.000000  3.000000
     max    5.000000  9.000000  5.000000
     mean   3.333333  6.333333  2.333333
     min    2.000000  3.000000  1.000000
     std    1.527525  3.055050  2.309401

我假設您需要在數據框中添加作為新列值的列的平均值。 請更正我。

您可以通過直接獲取列的平均值並通過指定類似來創建新列來實現

In [1]: import pandas as pd

In [2]: a = [{'date': 1,'a':2, 'b':3, 'c':5}, {'date':1, 'a':5, 'b':9, 'c':1}, {'date':1, 'a':3, 'b':7, 'c':1}]

In [3]: df = pd.DataFrame(a)

In [4]: for col in ['b','c']:
    ...:      df[col+"_mean"] = df.groupby('date')[col].transform('mean')

In [5]: df
Out[5]:
   a  b  c  date    b_mean    c_mean
0  2  3  5     1  6.333333  2.333333
1  5  9  1     1  6.333333  2.333333
2  3  7  1     1  6.333333  2.333333

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM