大家好。
Bronze Games Gender Gold Silver
1 1936 Male 2 3
Nan 1936 Female 1 1
我想重塑这个表,如下表所示,是否可能?
Male Female
Games Gold Silver Bronze Gold Silver Bronze
1936 2 3 1 1 1 NaN
1948 3 2 1 5 4 1
答案 0 :(得分:0)
我是pandas
的初学者所以我只得到这个(现在)。
import pandas as pd
data = {
'Bronze': [1, None, 1, 1],
'Games': [1936, 1936, 1948, 1948],
'Gender': ['Male', 'Female', 'Male', 'Female'],
'Gold': [2, 1, 3, 5],
'Silver': [3, 1, 2, 4],
}
df = pd.DataFrame(data)
print df
male = df[ df.Gender == 'Male' ]
female = df[ df.Gender == 'Female' ]
new_df = pd.merge(left=male, right=female, on='Games', suffixes=(' Male', ' Female'))
print new_df[ ['Games', 'Gold Male', 'Silver Male', 'Bronze Male', 'Gold Female', 'Silver Female', 'Bronze Female'] ]
数据:
Bronze Games Gender Gold Silver
0 1 1936 Male 2 3
1 NaN 1936 Female 1 1
2 1 1948 Male 3 2
3 1 1948 Female 5 4
结果:
Games Gold Male Silver Male Bronze Male Gold Female Silver Female Bronze Female
0 1936 2 3 1 1 1 NaN
1 1948 3 2 1 5 4 1