假设 df
是一个 pandas 数据框。
df.loc[]
只接受名称。df.iloc[]
只接受整数(实际位置)。df.ix[]
同时接受名称和整数:
当引用行时,df.ix[row_idx, ]
只想得到名称。例如:
df = pd.DataFrame({'a' : ['one', 'two', 'three','four', 'five', 'six'],
'1' : np.arange(6)})
df = df.ix[2:6]
print(df)
1 a
2 2 three
3 3 four
4 4 five
5 5 six
df.ix[0, 'a']
抛出错误,不会返回'two'。
在引用列时,iloc 更喜欢整数而非名称。例如:
df.ix[2, 1]
返回的是"three",而不是2(虽然df.idx[2, '1']
确实返回了2
)。
奇怪的是,我想要完全相反的功能。通常我的列名非常有意义,所以在我的代码中直接引用它们。但由于对观察数据进行了大量清理,我的Pandas数据框的行名称通常不对应于range(len(df))
。
我意识到我可以使用:
df.iloc[0].loc['a'] # returns three
但这看起来很丑!有没有人知道更好的方法来做到这一点,使得代码看起来像这样?
df.foo[0, 'a'] # returns three
事实上,我能否在pandas.core.frame.DataFrame
中添加自己的新方法,例如df.idx(rows, cols)
实际上是df.iloc[rows].loc[cols]
吗?
df['a'].iloc[0]
。 - unutbudf.loc[df.index[0], 'a']
。这种方法的优点在于不使用链式索引,因此可以在进行赋值操作时正常工作,而df[['a','b']].iloc[0] = val
则不行。 - unutbu