取一个单元格的值来表示 pandas 的列名 [英] Take a cell's value to indicate a column name in pandas

查看:68
本文介绍了取一个单元格的值来表示 pandas 的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入

      DBN Grade   3   4   5
0  01M015     3  30  44  15
1  01M015     4  30  44  15
2  01M015     5  30  44  15

所需的输出

      DBN Grade   3   4   5  Enrollment
0  01M015     3  30  44  15  30
1  01M015     4  30  44  15  44
2  01M015     5  30  44  15  15

您将如何创建注册"列?

How would you create the Enrollment column?

请注意,我们为每个记录寻找的列取决于df ['Grade']的值.

Note that the column we seek for each record depends on the value at df['Grade'].

我尝试了df [df ['Grade']]的变体这样我可以找到df ['3']列,但没有成功.

I've tried variations of df[df['Grade']] so that I could find the column df['3'], but I haven't been successful.

有没有一种方法可以简单地做到这一点?

Is there a way to do this simply?

import pandas as pd
import numpy as np

data={'DBN':['01M015','01M015','01M015'],
      'Grade':['3','4','5'],
      '3':['30','30','30'],
      '4':['44','44','44'],
      '5':['15','15','15']}

df = pd.DataFrame(data)

# This line below doesn't work: raises ValueError: Length of values does not match length of index
df['Enrollment'] = [df[c] if (df.loc[i,'Grade'] == c) else None for i in df.index for c
                    in df.columns]

推荐答案

设置索引,然后使用lookup:

df.set_index('Grade').lookup(df['Grade'], df['Grade'])

array(['30', '44', '15'], dtype=object)


如果数据为数字(在示例数据中为所有字符串),则可能会遇到一些问题,需要进行强制转换才能使查找成功.


You might run into some issues if your data is numeric (in your sample data it is all strings), requiring a cast to make the lookup succeed.

这篇关于取一个单元格的值来表示 pandas 的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆