[英]Issue plotting selected columns of a data-frame on a map based on the values of another column using pandas
[英]Groupby pandas data-frame based on values from another df
我有一個數據框,其中保留了所有相關屬性,另一個數據框具有基於我想對第一個 df 進行分組的屬性。
我知道如果你把一個系列(一列)作為參數,你可以按數據框分組,如果你把一個數據框你得到一個錯誤。
ValueError: Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional
我知道我可以將列連接到原始數據框,但我不想這樣做,除非沒有其他解決方案。
df.groupby([sorted_team_names]).ngroup()
這是我的代碼。 sorted_team_names 是一個有兩列的 df,而且它的索引與 df 相同。
這是一個相當普遍的問題,我不確定您是否需要數據樣本。
一種方法是分別按列分組:
df1 = pd.DataFrame({'a':[1,2,2,1], 'b':[1,2,2,1]})
print (df1)
a b
0 1 1
1 2 2
2 2 2
3 1 1
df2 = pd.DataFrame({'c':[1,2,3,7]})
print (df2)
c
0 1
1 2
2 3
3 7
df3 = df2.groupby([df1['a'], df1['b']]).sum()
print (df3)
c
a b
1 1 8
2 2 5
...但索引必須在兩個 DataFrame 之間匹配:
df1 = pd.DataFrame({'a':[1,2,2,1], 'b':[1,2,2,1]}, index=[2,5,6,8])
print (df1)
a b
2 1 1 <- matched only 2 index
5 2 2
6 2 2
8 1 1
df2 = pd.DataFrame({'c':[1,2,3,7]})
print (df2)
c
0 1
1 2
2 3
3 7
df3 = df2.groupby([df1['a'], df1['b']]).sum()
print (df3)
c
a b
1.0 1.0 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.