Pandas 新手,我很难找到这个问题的答案。
给定以下数据框:
类别 | foo_count | bar_count | 蝙蝠计数 |
---|---|---|---|
富 | 10 | 20 | 30 |
酒吧 | 10 | 20 | 30 |
蝙蝠 | 10 | 20 | 30 |
我想生成一个新列,其中仅包含类别值与列名称匹配的值,以便最终的 DataFrame 如下所示:
类别 | 数 |
---|---|
富 | 10 |
酒吧 | 20 |
蝙蝠 | 30 |
我觉得这个问题的答案可能非常简单,需要
map
功能以及某种形式的重新索引,但对于我来说,我根本无法让它发挥作用。非常感谢您的帮助,因为我不知道下一步该做什么!
我不确定我的理解是否正确。 但例如,如果您想获取其中列为 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']]