如何使用列作为索引将单元格放在pandas数据框中的某个位置

时间:2016-06-06 07:08:46

标签: python pandas indexing dataframe

示例数据框:

class   fred    bill
0   a   23  35
1   b   123 45
2   c   34  45
3   d   4   45

(pandas添加了不需要的索引(0-> 3)

我想要的是说:

fred_b_class = df.at['fred','b'] 
>>> 123

我尝试将列'class'设置为pd.set_index('class')

的索引

但是,在致电df.index.name时,它返回了none

2 个答案:

答案 0 :(得分:2)

我认为你需要来自class列的set_index,然后在at中交换参数,因为第一个参数是索引和第二列名称:

df = df.set_index('class')
#df.set_index('class', inplace=True)
print (df)
       fred  bill
class            
a        23    35
b       123    45
c        34    45
d         4    45

print (df.at['b','fred'] )
123

答案 1 :(得分:0)

这个解决方案如何,如果由于某种原因您不打算用dataframe列替换现有索引

df['fred'][df.class=='b']