python - 如何使用一行中单元格的值来选择在 pandas 数据框中查找列名?

标签 python pandas

我有一个看起来像这样的数据框

   Index  Variable1  Value1  Variable2  Value2  Cat  Dog  Cow
    1      Cat        7       Sheep      7       0    0    0
    2      Sheep      2       Cat        6       0    0    0
    3      Cow        3       Dog        2       0    0    0

当 Variable 列等于适当的列名时,如何使用 Value 列中的值有效地填充 Cat、Dog 和 Cow 列?所以它看起来像这样

Index  Variable1  Value1  Variable2  Value2  Cat  Dog  Cow
1      Cat        7       Sheep      7       7    0    0
2      Sheep      2       Cat        6       6    0    0
3      Cow        3       Dog        2       0    2    3

我制作了一个嵌套的 for 循环,循环遍历每个“变量”列,然后循环遍历该列中的每一行,根据该单元格中的值填充每只动物的数据。但我 100% 确定这样做的方式很糟糕。

最佳答案

#create variables
vals = df.filter(like = 'Value').columns
variables = df.filter(like = 'Variable').columns
animals = df.iloc[:,-3:].columns

#lump all 'Variable_' and 'Value_' into one df
res = pd.concat(df.filter(ent).set_axis(['val','var'],axis=1) for ent in zip(vals,variables))
res

    val var
0   7   Cat
1   2   Sheep
2   3   Cow
0   7   Sheep
1   6   Cat
2   2   Dog

#pivot res
out = (res
       .pivot(columns='var',values='val')
       .fillna(0)
       .astype(int)
       .filter(animals)
      )
out


var Cat Dog Cow
0   7   0   0
1   6   0   0
2   0   2   3

#final result
result = pd.concat([df.iloc[:,:-3],out],axis=1)
result


  Index Variable1   Value1  Variable2   Value2  Cat Dog Cow
0   1     Cat         7      Sheep       7       7   0   0
1   2     Sheep       2      Cat         6       6   0   0
2   3     Cow         3      Dog         2        0  2   3

关于python - 如何使用一行中单元格的值来选择在 pandas 数据框中查找列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61394646/

相关文章:

python - 具有多个 Pandas DataFrame 的并排箱线图

python - 使用前向填充缺失日期为每个 ID 添加每日数据

Python:为什么 partition(sep) 比 split(sep, maxsplit=1) 快

python - 如何获得条目小部件来保存我输入的内容? Python Tkinter

python - 如何使用列上的尾随行对同一列进行计算 | Pandas python

python - 如何将"is"或“否”更改为二元分类?

python - 如何修复 Python 中的循环导入错误

python - Python 中的正则表达式分组

python - 有没有办法在 sklearn 管道中链接 pd.cut FunctionTransformer?

python - Pandas 过滤和比较日期