我正在尝试移动我的一些行并使它们成为列,但保持数据框的大部分不变。
我的数据框看起来像这样:
ID Thing Level1 Level2 Time OAttribute IsTrue Score Value
1 bicycle value value 9:30 whatever yes 1 type1
2 non-cycle value value 1:30 whatever no 2 type2
3 bicycle value value 2:30 whatever yes
4 bicycle value value 3:30 whatever no 4 type3
我想要这样的东西:
ID Thing Level1 Level2 Time OAttribute IsTrue Type1 Type2 Type 3
1 bicycle value value 9:30 whatever yes 1
2 non-cycle value value 1:30 whatever no 2
3 bicycle value value 2:30 whatever yes
4 bicycle value value 3:30 whatever no 4
最佳答案
选项 1
使用合并
df_ = df[['ID', 'Value']].dropna().set_index('Value', append=True).ID.unstack()
df.drop('Value', 1).merge(df_, right_index=True, left_index=True, how='left').fillna('')
选项 2
使用 pd.concat
df_ = df[['ID', 'Value']].dropna().set_index('Value', append=True).ID.unstack()
pd.concat([df, df_], axis=1).drop('Value', 1).fillna('')
关于python - 将行转列,同时保持部分数据框完好无损,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39415851/