I have this data that I want to unpivot and melt into columns. The data is a multi-header table. I have a sample dictionary of the data.
Edit here___
I don't know how to convert a dictionary with multiple keys like I had shown previously into a df so let's restructure the dictionary like so...
data = {
"id": {
0: "month",
1: "11/30/2021",
2: "12/31/2021",
3: "1/31/2022",
4: "2/28/2022",
5: "3/31/2022",
},
"A48": {0: "storage", 1: "0", 2: "29", 3: "35", 4: "33", 5: "30"},
"A48.1": {0: "use", 1: "0", 2: "1", 3: "0", 4: "0", 5: "0"},
"A62": {0: "direct", 1: "0", 2: "0", 3: "2", 4: "3", 5: "2"},
"A62.1": {0: "storage", 1: "0", 2: "57", 3: "69", 4: "65", 5: "59"},
"A62.2": {0: "use", 1: "0", 2: "1", 3: "0", 4: "0", 5: "0"},
}
Now let's get the Dataframe...
dfc = pd.DataFrame.from_dict(data)
dfc.columns=pd.MultiIndex.from_arrays([dfc.columns,dfc.iloc[0]])
dfc = dfc.iloc[2:].reset_index(drop=True)
Which looks like this:
id A48 A48.1 A62 A62.1 A62.2
month storage use direct storage use
0 12/31/2021 29 1 0 57 1
1 1/31/2022 35 0 2 69 0
2 2/28/2022 33 0 3 65 0
3 3/31/2022 30 0 2 59 0
What I am looking for is a table like this.
| month | id | direct | storage | use |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 11/30/2021 | A48 | NaN | 0 | 0 |
| 12/31/2021 | A48 | NaN | 29 | 1 |
| 1/31/2022 | A48 | NaN | 35 | 0 |
| 2/28/2022 | A48 | NaN | 33 | 0 |
| 3/31/2022 | A48 | NaN | 30 | 0 |
| 11/30/2021 | A62 | 0 | 0 | 0 |
| 12/31/2021 | A62 | 0 | 57 | 1 |
| 1/31/2022 | A62 | 2 | 69 | 0 |
| 2/28/2022 | A62 | 3 | 65 | 0 |
| 3/31/2022 | A62 | 2 | 59 | 0 |
1条答案
按热度按时间6ojccjat1#
为以后使用定义以下helper函数:
然后,使用Pandasmelt、concat和merge方法:
最后道: