我正在尝试以这种方式来透视数据,以使我得到诸如AK_positive AK_probableCases,AK_negative,AL_positive ..等列。
您可以在此处获取数据,df = pd.read_csv('https://covidtracking.com/api/states/daily.csv')
答案 0 :(得分:0)
只需使用.to_flat_index()将原始MultiIndex列展平为元组,然后将元组元素重新排列为新的列名。
df_pivoted.columns = [f"{i[1]}_{i[0]}" for i in df_pivoted.columns.to_flat_index()]
结果:
# start from April
df_pivoted[df_pivoted.index >= 20200401].head(5)
AK_positive AL_positive AR_positive ... WI_grade WV_grade WY_grade
date ...
20200401 133.0 1077.0 584.0 ... NaN NaN NaN
20200402 143.0 1233.0 643.0 ... NaN NaN NaN
20200403 157.0 1432.0 704.0 ... NaN NaN NaN
20200404 171.0 1580.0 743.0 ... NaN NaN NaN
20200405 185.0 1796.0 830.0 ... NaN NaN NaN