我的問題是我無法轉換它:
import pandas as pd
example = {
"ID": [1, 1, 2, 2, 2, 3],
"place":["Maryland","Maryland", "Washington", "Washington", "Washington", "Los Angeles"],
"sex":["male","male","female", "female", "female", "other"],
"depression": [0, 0, 0, 0, 0, 1],
"stressed": [1 ,0, 0, 0, 0, 0],
"sleep": [1, 1, 1, 0, 1, 1],
"ate":[0,1, 0, 1, 0, 1],
}
#load into df:
example = pd.DataFrame(example)
print(example)
對此:
import pandas as pd
result = {
"ID": [1, 2, 3],
"place":["Maryland","Washington","Los Angeles"],
"sex":["male", "female", "other"],
"depression": [0, 0, 1],
"stressed": [1,0,0],
"sleep": [1, 1, 1],
"ate":[1, 1 , 1],
}
#load into df:
result = pd.DataFrame(result)
print(result)
我試影像這樣旋轉它:
table = example.pivot_table(index='place',columns='ID')
print (table)
但是,它看起來完全不同,我很困惑如何為其設定值。你能否讓我知道我做錯了什么。
非常感謝提前!
uj5u.com熱心網友回復:
您可以使用groupby
andany
到達那里:
example.groupby(['ID','place','sex']).any().astype(int).reset_index()
ID place sex depression stressed sleep ate
0 1 Maryland male 0 1 1 1
1 2 Washington female 0 0 1 1
2 3 Los Angeles other 1 0 1 1
uj5u.com熱心網友回復:
我認為您只希望groupby
使用max
(它作為 1/0 值的邏輯 OR)作為聚合函式:
example.groupby(['ID', 'place','sex']).max().reset_index()
輸出:
ID place sex depression stressed sleep ate
0 1 Maryland male 0 1 1 1
1 2 Washington female 0 0 1 1
2 3 Los Angeles other 1 0 1 1
uj5u.com熱心網友回復:
默認聚合函式是均值,為了保持二進制,使用aggfunc='max'
:
table = example.pivot_table(index='place', columns='ID', aggfunc=np.max, fill_value=0)
輸出:
stressed
ID 1 2 3
place
Los Angeles 0 0 0
Maryland 1 0 0
Washington 0 0 0
雖然在你的情況下你可能想要一個Groupby.max
:
example.groupby(['ID', 'place', 'sex'], as_index=False).max()
輸出:
ID place sex depression stressed sleep ate
0 1 Maryland male 0 1 1 1
1 2 Washington female 0 0 1 1
2 3 Los Angeles other 1 0 1 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495448.html
上一篇:將兩個字典連接在一起
下一篇:如何按帶有時區的日期時間列分組?