如何用同一行中的列值替换列表中的列名?

huangapple go评论70阅读模式
英文:

How do I replace column names in a list with column values in the same row?

问题

我有一个数据框,其中一列列出了最大值列的名称,根据这些名称,我想将它们替换为同一行上的相应列值

Max Column A Column B Column C
Column C 200 500 800
Column A 600 700 1000

预期输出应为:

Max Column A Column B Column C
800 200 500 800
600 600 700 1000

我不确定最好的解决方法是什么,任何帮助将不胜感激!
这只是一个示例列表,实际列表更大且更随机。

英文:

I've got a dataframe where 1 column lists Max value column names, Based on the names I'd like to replace them with those column values on the same row

Max Column A Column B Column C
Column C 200 500 800
Column A 600 700 1000

Expected output should be:

Max Column A Column B Column C
800 200 500 800
600 600 700 1000

I'm not sure what the best way to tackle this would be, any help would be greatly appreciated!

This is a sample list, the actual list is larger and more randomized

答案1

得分: 2

以下是翻译好的代码部分:

import pandas as pd

df = pd.DataFrame(
    {
        'Max': ['Column C', 'Column A'],
        'Column A': [200, 600],
        'Column B': [500, 700],
        'Column C': [800, 1000]
    }
)

df['Max'] = df.apply(lambda x: x[x['Max']], axis=1)

Explanation: 按行应用 x[x['Max']] 来获取列名对应的值。

英文:

Here's what you could try:

import pandas as pd

df = pd.DataFrame(
    {
        'Max': ['Column C', 'Column A'],
        'Column A': [200,600],
        'Column B': [500,700],
        'Column C': [800, 1000]
    }
)

df['Max'] = df.apply(lambda x: x[x['Max']], axis=1)

Explanation: apply x[x['Max']] row wise to get the value of the column name

huangapple
  • 本文由 发表于 2023年7月3日 10:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定