根据另一列的值按列*标签*返回数据

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

Pandas 新手,我很难找到这个问题的答案。

给定以下数据框:

类别 foo_count bar_count 蝙蝠计数
10 20 30
酒吧 10 20 30
蝙蝠 10 20 30

我想生成一个新列,其中仅包含类别值与列名称匹配的值,以便最终的 DataFrame 如下所示:

类别
10
酒吧 20
蝙蝠 30

我觉得这个问题的答案可能非常简单,需要

map
功能以及某种形式的重新索引,但对于我来说,我根本无法让它发挥作用。非常感谢您的帮助,因为我不知道下一步该做什么!

pandas dataframe
1个回答
0
投票

我不确定我的理解是否正确。 但例如,如果您想获取其中列为 count_name 的行计数,您可以应用函数来创建列。

# Function to apply to each row
def extract_count(row):
    category = row['category']
    count_col = f"{category}_count"
    return row.get(count_col, None)

# Applying the function and creating the new 'count' column
df['count'] = df.apply(extract_count, axis=1)

该函数应用于axis=1,并根据类别名称获取列的名称。

然后用两列构造新数据:

# Resulting DataFrame
df = df[['category', 'count']]
© www.soinside.com 2019 - 2024. All rights reserved.