我有一个带有偏移索引的数据框,我想访问感兴趣列的第一个值:
df = pd.DataFrame({"a": [0,1,2], "b":[3,4,5]}, index=[5,6,7])
In [20]: df
Out[20]:
a b
5 0 3
6 1 4
7 2 5
没有 .ix、.loc methods of pandas dataframe没有帮助(或者我使用它们不合适):</p>
In [24]: df.ix[0,"a"]
KeyError: 0
In [27]: df["a"][0]
KeyError: 0
我可以用reset_index来做到这一点方法,但我想保留原始数据框
我找到了解决方案,但我认为这不是最好的:
In [29]: df["a"].values[0]
Out[29]: 0
最佳答案
使用iloc[0]
访问第一个元素:
In [193]:
print(df['a'].iloc[0])
print(df['b'].iloc[0])
0
3
或头
:
In [194]:
df.head(1)
Out[194]:
a b
5 0 3
关于python - 使用偏移索引获取 pandas 中数据帧中列的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646005/