1 回答

TA貢獻1862條經驗 獲得超6個贊
使用DataFrame.set_index
withDataFrame.unstack
和DataFrame.sort_index
for new?DataFrame
with?MultiIndex
,然后用 s 壓平它f-string
,最后通過 將其添加到原始的DataFrame.join
:
df1 = df.set_index('Code', append=True).unstack().sort_index(axis=1, level=1)
df1.columns = df1.columns.map(lambda x: f'{x[1]}_{x[0]}')
df = df.join(df1)
print (df)
? Code? Freq1? Freq2? A01_Freq1? A01_Freq2? B02_Freq1? B02_Freq2? C03_Freq1? \
0? A01? ? ? 1? ? ? 7? ? ? ? 1.0? ? ? ? 7.0? ? ? ? NaN? ? ? ? NaN? ? ? ? NaN? ?
1? B02? ? ? 0? ? ? 6? ? ? ? NaN? ? ? ? NaN? ? ? ? 0.0? ? ? ? 6.0? ? ? ? NaN? ?
2? C03? ? ?17? ? ? 8? ? ? ? NaN? ? ? ? NaN? ? ? ? NaN? ? ? ? NaN? ? ? ?17.0? ?
? ?C03_Freq2??
0? ? ? ? NaN??
1? ? ? ? NaN??
2? ? ? ? 8.0??
添加回答
舉報