Pandas 基于另一列的值的新列

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

如何向数据框中添加与另一列中的值同名的新列?

我的数据框是:

import pandas as pd
df = pd.DataFrame({
    'Col1': [2, 74, 37, 36, 95],
    'Col2': [36, 80, 9, 26, 16],
    'Col3': [20, 4, 7, 55, 91],
    'Col4': ['Col2','Col2','Col2','Col2','Col2']
})

因此,我需要添加新列“Col0”,其中包含“Col2”列中的值,因为它的名称与 Col4 中的值相同。

我想要的结果是:

df = pd.DataFrame({
    'Col1': [2, 74, 37, 36, 95],
    'Col2': [36, 80, 9, 26, 16],
    'Col3': [20, 4, 7, 55, 91],
    'Col4': ['Col2','Col2','Col2','Col2','Col2'],
    'Col0': [36, 80, 9, 26, 16]
})
python pandas
1个回答
0
投票

尝试:

df["Col0"] = df.apply(lambda row: row[row["Col4"]], axis=1)
print(df)

打印:

   Col1  Col2  Col3  Col4  Col0
0     2    36    20  Col2    36
1    74    80     4  Col2    80
2    37     9     7  Col2     9
3    36    26    55  Col2    26
4    95    16    91  Col2    16
© www.soinside.com 2019 - 2024. All rights reserved.