gpt4 book ai didi

python - 按整数索引 Pandas 数据帧

转载 作者:太空狗 更新时间:2023-10-29 18:03:15 25 4
gpt4 key购买 nike

我似乎找不到一种优雅的方式来 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

supersedes irow 方法。

最佳答案

df['A'].ix[0] 出现错误,因为您的索引不是从 0 开始,而是从 10 开始。您可以通过以下任一方法获得所需的值以下的

df['A'].ix[10]
df['A'].irow(0)

第一个使用正确的索引。第二个命令,我怀疑是你想要的,通过行号而不是索引值找到值,并且在技术上只比 if df['A'].ix[0]< 长两个字符 成功了。

或者,您可以重置索引,以便它们以您期望的方式响应 df['A'].ix[0]:

df2=df.reset_index()

这将保留您的旧索引(10、20 等),方法是将它们移动到 df2 数据框中名为“索引”的列中。然后 df2['A'].ix[0] 将返回 'a'。如果要删除旧的基于 10 的索引,可以将标志 drop=True 插入 reset_index 函数的括号中。

关于python - 按整数索引 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11621165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com