【发布时间】:2012-07-23 21:57:01
【问题描述】:
我似乎无法通过整数索引找到index 和pandas.DataFrame 的优雅方式。
在下面的示例中,我想从'A' 列的第一个元素中获取值“a”。
import pandas
df = pandas.DataFrame(
{'A':['a','b', 'c'], 'B':['f', 'g', 'h']},
index=[10,20,30]
)
我希望df['A'].ix[0] 和df['A'][10] 都返回'a'。
df['A'][10] 确实返回 'a',但 df['A'].ix[0] 抛出 KeyError: 0。我能想到的根据索引 0 获取值 'a' 的唯一方法是使用以下方法。
df['A'][df['A'].index[0]]
有没有更短的方法可以使用 0 索引将'a' 从数据框中取出?
更新
从 pandas 0.11 开始,index by integer 有另一种方式。
df.iloc[0] # integer based, gives the first row
df.loc[10] # label based, gives the row with label 10
这种supersedesirow 方法。
【问题讨论】: