Pandas - 使用其他列值作为列名选择列 [英] Pandas - select column using other column value as column name
问题描述
我有一个包含一列的数据框,我们称之为名称".名称"具有其他列的名称.我想添加一个新列,该列将根据名称"中包含的列名称为每一行提供值.列.
示例:
输入数据框:pd.DataFrame.from_dict({"a": [1, 2, 3,4], "b": [-1,-2,-3,-4], "names":['a','b','a','b']})
输出数据帧:pd.DataFrame.from_dict({"a": [1, 2, 3,4], "b": [-1,-2,-3,-4], "names":['a','b','a','b'], "new_col":[1,-2,3,-4]})
您可以使用 查找
:
df['new_col'] = df.lookup(df.index, df.names)df# a b 命名为 new_col#0 1 -1 1#1 2 -2 b -2#2 3 -3 3#3 4 -4 b -4
I have a dataframe that contains a column, let's call it "names". "names" has the name of other columns. I would like to add a new column that would have for each row the value based on the column name contained on that "names" column.
Example:
Input dataframe:
pd.DataFrame.from_dict({"a": [1, 2, 3,4], "b": [-1,-2,-3,-4], "names":['a','b','a','b']})
a | b | names | --- | --- | ---- | 1 | -1 | 'a' | 2 | -2 | 'b' | 3 | -3 | 'a' | 4 | -4 | 'b' |
Output dataframe:
pd.DataFrame.from_dict({"a": [1, 2, 3,4], "b": [-1,-2,-3,-4], "names":['a','b','a','b'], "new_col":[1,-2,3,-4]})
a | b | names | new_col | --- | --- | ---- | ------ | 1 | -1 | 'a' | 1 | 2 | -2 | 'b' | -2 | 3 | -3 | 'a' | 3 | 4 | -4 | 'b' | -4 |
You can use lookup
:
df['new_col'] = df.lookup(df.index, df.names)
df
# a b names new_col
#0 1 -1 a 1
#1 2 -2 b -2
#2 3 -3 a 3
#3 4 -4 b -4
这篇关于Pandas - 使用其他列值作为列名选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!