如何将 pandas 数据框中两行的值压缩到一个新行中?

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

我有一个数据框,其中标题行和第一行看起来像这样:

索引 1 2
0 字符串1 字符串2
1 int_val1 int_val2

我希望它看起来像这样:

索引 字符串1_1 字符串2_2
0 int_val1 int_val2

我怀疑可能有一种更以熊猫为导向的方法来解决这个问题,但我一生都找不到一种方法。因此,我尝试将两个相关行视为列表,并使用

zip()
函数创建一个新列表并将其用作标题行。为了实现这一点,我首先尝试将标题行转换为整数,如下所示:

df = df.columns.astype(str)
new_headers = [x + y for x, y in zip(df.loc[0], df.columns)]

但是,这会返回

AttributeError: 'Index' object has no attribute 'loc'
,这似乎是因为我将原始标头转换为字符串,出于我不完全理解的原因。

有更好的方法来完成我想做的事情吗?或者我的拉链缺少什么东西?为了完成此任务,我将手动重命名列,然后删除无关的行,但我想知道是否有更 Pythonic/Pandan 的方法来执行此操作。

python pandas zip list-comprehension
1个回答
0
投票

您的错误是由于

df = df.columns.astype(str)
将索引重新分配给
df

假设

index
是索引,您可以使用:

# update the columns
df.columns = list(map('_'.join, zip(df.iloc[0], df.columns.astype(str))))
# or
# df.columns = [x + y for x, y in zip(df.loc[0], df.columns.astype(str))]

# delete first row
df.drop(0, inplace=True)

# decrement index
df.index -= 1

print(df)

输出:

  string1_1 string2_2
0  int_val1  int_val2

使用的输入:

df = pd.DataFrame({1: ['string1', 'int_val1'],
                   2: ['string2', 'int_val2']})
© www.soinside.com 2019 - 2024. All rights reserved.