我有一个看起来像这样的DataFrame
id question feedback answer correct False_Answer01 False_Answer02 False_Answer03
1 q1 f1 a1-1 1 NaN NaN NaN
1 q1 f1 a1-2 0 NaN NaN NaN
1 q1 f1 a1-3 0 NaN NaN NaN
1 q1 f1 a1-4 0 NaN NaN NaN
2 q2 f2 a2-1 1 NaN NaN NaN
我想将所有False Answers
插入False Answer
列-错误答案是correct
== 0的答案。所以我想要这样的东西
id question feedback answer False_Answer01 False_Answer02 False_Answer03
1 q1 f1 a1-1 a1-2 a1-3 a1-4
我该怎么办?
答案 0 :(得分:0)
这更像是pivot
问题
df1=df.query('correct==1').copy()
df2=df.query('correct==0').copy()
df2['key']=df2.groupby(['id','question','feedback']).cumcount()+1
df2=df2.pivot_table(index=['id','question','feedback'],columns='key',values='answer',aggfunc='sum').add_prefix('False_Answer')
df=df1.dropna(1).merge(df2.reset_index(),how='left')
df
Out[388]:
id question feedback ... False_Answer1 False_Answer2 False_Answer3
0 1 q1 f1 ... a1-2 a1-3 a1-4
1 1 q2 f2 ... NaN NaN NaN
[2 rows x 9 columns]