Python重组Dataframe,将列名移动到行,重塑datafram

2024-04-24 01:24:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将df1转换为df2:

import pandas as pd
from pandas import DataFrame, Series

import numpy as np

df1 = pd.DataFrame(index=['date_1', 'date_2', 'date_3'], 
              columns=["A_count", "A_dollar", "B_count", "B_dollar"], 
              data=[[10,"$100",7,"$786"], [3,"$43",6,"$88"],     [5,"$565",8,"$876"]])
df1

enter image description here

基本上我需要的是将项目(A和B)作为标签放在一个新列中,然后将第3列和第4列的数据移动到项目下的每一行。这样我们每次约会都会有新的一排。在

enter image description here


Tags: 项目fromimportnumpydataframepandasdateas
1条回答
网友
1楼 · 发布于 2024-04-24 01:24:11

您可以使用下划线将列拆分为多索引,然后使用stack将其重塑为长格式:

df1.columns = df1.columns.str.split("_", expand=True)
df1.stack(level=0).rename_axis((None, "item")).reset_index("item")

enter image description here

如果列名中有多个下划线,如下所示:

^{pr2}$

enter image description here

您可以将rsplitn = 1一起使用,以便它只在最后一个下划线上拆分:

df1.columns = df1.columns.str.rsplit("_", n=1, expand=True)
df1.stack(level=0).rename_axis((None, "item")).reset_index("item")

enter image description here

相关问题 更多 >