【问题标题】:How can I unpivot data with multiple columns and multiple variables in pandas?如何在 pandas 中使用多列和多个变量取消透视数据?
【发布时间】:2020-08-25 13:07:52
【问题描述】:

如何在 pandas 中取消透视具有多列和多个变量的数据?

我的意见:

并渴望输出:

【问题讨论】:

标签: pandas unpivot melt


【解决方案1】:

删除 Na,添加列名,并将值“追加()”到空的“DataFrame”。

    product ene ene_total   feb feb_total   mar mar_total
0   A   NaN NaN 2.0 218.75  NaN NaN
1   B   NaN NaN 1.0 27.40   NaN NaN
2   C   NaN NaN NaN NaN 24.0    1530.00
3   D   NaN NaN NaN NaN 24.0    1102.50
4   E   NaN NaN NaN NaN 12.0    206.79
5   F   NaN NaN NaN NaN 24.0    317.14
6   G   6.0 98.89   NaN NaN NaN NaN
7   H   NaN NaN NaN NaN 24.0    385.29
8   I   NaN NaN NaN NaN 25.0    895.98

new_df = pd.DataFrame(index=[], columns=[0,1,2,3])

for i in range(len(df)):
    tmp = df.iloc[i].dropna()
    new_df = new_df.append(pd.Series([tmp.index[1],tmp[0],tmp[1],tmp[2]]), ignore_index=True)

new_df.rename(columns={0:'period', 2:'unit', 3:'total'}).set_index(1)

    period  unit    total
1           
A   feb 2.0     218.75
B   feb 1.0     27.40
C   mar 24.0    1530.00
D   mar 24.0    1102.50
E   mar 12.0    206.79
F   mar 24.0    317.14
G   ene 6.0     98.89
H   mar 24.0    385.29
I   mar 25.0    895.98

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    相关资源
    最近更新 更多