[英]How to build a statement to perform a groupby operation during runtime on a Pandas DataFrame?
我有一個 Pandas DataFrame dfs
和一個列表headers
列表headers
在運行時被分配了 DataFrame dfs
的列名。
例如,讓我們考慮使用dfs
的列名分配列表:
["Information_type", "Interface", "Type_of_Interface", "Connection_Mechanism"]
我想在 DataFrame dfs
上執行以下groupby
和agg
操作,而無需明確提及 groupby 操作中的列名,即"Information_type": " ".join
”.join, "Interface": " ".join
:“”.join, "Type_of_Interface": " ".join
, "Connection_Mechanism": " ".join
:
dfs[0]=dfs[0].groupby("grp").agg({"Information_type": " ".join, "Interface": " ".join, "Type_of_Interface": " ".join, "Connection_Mechanism": " ".join})
基本上在運行時將"Information_type": " ".join, "Interface": " ".join, "Type_of_Interface": " ".join, "Connection_Mechanism": " ".join
寫入上述行。
如果這樣的事情是可能的,那就太好了,否則我將不得不手動編輯列名並為每個表執行groupby
和agg
操作!
感謝你的幫助。 提前致謝!
IIUC 這就是你想要的:
#setup
df = pd.DataFrame({'a':np.random.randint(0,5,25),
'b':np.random.randint(0,5,25),
'c':np.random.randint(0,5,25),
'd':np.random.randint(0,5,25)}, dtype = str)
cols = ['b','c']
df.groupby('a').agg({col: " ".join for col in cols})
Output
b c
a
0 0 0 3 3 4 2 3 3 3 4 0 4 3 2
1 2 4 1 2 1 3 0 2 1 3
2 0 0 4 2 1 3 1 3
3 2 2 4 1 3 0 3 1 1 1 2 0
4 4 2 0 2 0 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.