Rya*_*Kao 4 python indexing dataframe pandas
我有一个数据集,其中包含贡献者的 id 和contributor_message。我想检索具有相同消息的所有样本,例如,contributor_message == '我支持此提案,因为......'。
我使用 data.loc[data.contributor_message == '我支持这个提案,因为...'].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
Run Code Online (Sandbox Code Playgroud)
您有两种选择来解决此问题。
选项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
Run Code Online (Sandbox Code Playgroud)