输入
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
所需的输出
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]
您将如何创建“注册”列?
请注意,我们为每个记录寻找的列取决于df ['Grade']的值。
我尝试了df [df ['Grade']]的variations,以便可以找到df ['3']列,但是没有成功。
有没有办法做到这一点?
<html>
<body>
<script>
function multa(a, b) {
return c;
var a = 3;
var b = 4;
}
alert(a * b + "is" + c);
</script>
</body>
</html>
答案 0 :(得分:4)
设置索引,然后使用lookup
:
df.set_index('Grade').lookup(df['Grade'], df['Grade'])
array(['30', '44', '15'], dtype=object)
如果数据为数字(在示例数据中为所有字符串),则可能会遇到一些问题,需要进行强制转换才能使查询成功。
答案 1 :(得分:1)
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)
enrollmentList = []
for index, row in df.iterrows():
enrollmentList.append(row[row["Grade"]])
df['Enrollment'] = enrollmentList