簡體   English   中英

從另一個(相同的行數)數據框中按列分組

[英]Groupby a column from another (same # of rows) dataframe

假設我有兩個簡單的數據框:

x1 = pd.DataFrame({'a':[1,2,3,4],
                   'b':[10,10,20,20],  
                   'c':['z','z','z','o']})
x2 = pd.DataFrame({'e':['foo', 'bar', 'foo', 'foo'], 
                   'f':['baz', 'blah', 'baz', 'blah']})
> x1
   a   b  c
0  1  10  z
1  2  10  z
2  3  20  z
3  4  20  o
> x2
     e     f
0  foo   baz
1  bar  blah
2  foo   baz
3  foo  blah

我想根據x2的列將函數應用於x1組。 例如:

x1['avg'] = x1.groupby(x2[['e', 'f']])['a'].transform(np.mean)
*** ValueError: Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional

但是我得到這個值錯誤。

如果groupby拆分來自x1,則不會發生該錯誤(但我不想為x1分配x2列,出於代碼清潔的原因,我不再贅述。

x1.groupby(['b', 'c'])['a'].transform(np.mean)
0    1.5
1    1.5
2    3.0
3    4.0

為什么會這樣/我能解決嗎?

您可以將兩列壓縮在一起,然后groupby對的元組傳遞給groupby

>>> x1.groupby(zip(x2['e'], x2['f']))['a'].transform(np.mean)
0    1
1    2
2    3
3    4
Name: a, dtype: int64

您不能傳遞DataFrame,但可以傳遞Series的(列表):

In [11]: x1.groupby([x2.e, x2.f])["a"].transform("mean")
Out[11]:
0    2
1    2
2    2
3    4
dtype: int64

更一般而言,您可以使用列表理解功能(如果要按另一個DataFrame中的所有列進行分組):

In [12]: x1.groupby([x2[col] for col in x2])["a"].transform("mean")
Out[12]:
0    2
1    2
2    2
3    4
dtype: int64

話雖如此,繼續進行連接可能會更好。...IMO保持變量獨立通常是一個好主意。

暫無
暫無

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

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