gpt4 book ai didi

python - Pandas:使用 iloc 检索数据与输入索引不匹配

转载 作者:行者123 更新时间:2023-12-05 02:16:28 26 4
gpt4 key购买 nike

我有一个包含贡献者 ID 和贡献者消息的数据集。我想检索所有带有相同消息的样本,例如,contributor_message == '我支持这个提议,因为......'。

我使用 data.loc[data.contributor_message == 'I support this proposal because...'].index -> 所以基本上你可以使用相同的消息在 DataFrame 中获取索引,假设这些索引为 1, 2, 50, 9350, 30678,...

然后我尝试了 data.iloc[[1,2,50]],这给了我正确的答案,即索引与 DataFrame 索引匹配。

但是,当我使用 data.iloc[9350] 或更高的索引时,我将获得相应的 DataFrame 索引。假设我这次在 DataFrame 中得到了 15047。

谁能建议如何解决这个问题?

最佳答案

当您的索引未与其整数位置对齐时,就会发生这种情况。

请注意 pd.DataFrame.loc用于按索引和 pd.DataFrame.iloc 切片用于按整数位置切片。

下面是一个最小的例子。

df = pd.DataFrame({'A': [1, 2, 1, 1, 5]}, index=[0, 1, 2, 4, 5])

idx = df[df['A'] == 1].index

print(idx) # Int64Index([0, 2, 4], dtype='int64')

res1 = df.loc[idx]
res2 = df.iloc[idx]

print(res1)
# A
# 0 1
# 2 1
# 4 1

print(res2)
# A
# 0 1
# 2 1
# 5 5

您有 2 个选项来解决此问题。

选项 1

使用pd.DataFrame.loc按索引切片,如上。

选项 2

重置索引并使用pd.DataFrame.iloc:

df = df.reset_index(drop=True)
idx = df[df['A'] == 1].index

res2 = df.iloc[idx]

print(res2)
# A
# 0 1
# 2 1
# 3 1

关于python - Pandas:使用 iloc 检索数据与输入索引不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49960597/

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