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

问题描述 投票:0回答:1

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

我的输入:“输入”

和愿望输出:“期望输出”

pandas unpivot melt
1个回答
0
投票

删除Na,添加列名,并将值“ append()”添加到空的“ 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
© www.soinside.com 2019 - 2024. All rights reserved.