英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论