英文:
After dropping pandas DataFrame rows, How to still locate a row by the same index?
问题
当你从DataFrame中删除一行时,后续的行会随着它们的索引向上移动。但如果你尝试按原始索引定位一行,你会得到一个与预期不同的行,因为索引值已被重置以反映DataFrame中行的新位置。我想仍然能够按照原始索引定位任何一行。
例如:
这是在删除第0和第2行之前和之后的情况。
如何仍然能够获取索引为1的行?
英文:
When you delete a row from a DataFrame, the subsequent rows will shift up with their indexes.. but if you try to locate a row by its index.. you get a different row than expected because the index values have been reset to reflect the new positions of the rows in the DataFrame...
and I want to still be able to locate any of the rows by their original index
for example:
this is before and after I dropped 0 and 2 rows
before:
after:
and this is what I get when I locate the row with index 1:
how can I still get the row with index 1 ???
答案1
得分: 1
使用.loc
按索引名称索引数据框:
df = pd.DataFrame([4,3,2,1])
df.drop([0,2], inplace=True)
# 返回一个Series
df.loc[1,:]
# 或者返回一个DataFrame
df.loc[[1],:]
英文:
Use .loc
to index the dataframe by the index name:
df = pd.DataFrame([4,3,2,1])
df.drop([0,2], inplace=True)
# To return a Series
df.loc[1,:]
# Or to return a DataFrame
df.loc[[1],:]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论