在删除 pandas DataFrame 行之后,如何仍然通过相同的索引定位一行?

huangapple go评论61阅读模式
英文:

After dropping pandas DataFrame rows, How to still locate a row by the same index?

问题

当你从DataFrame中删除一行时,后续的行会随着它们的索引向上移动。但如果你尝试按原始索引定位一行,你会得到一个与预期不同的行,因为索引值已被重置以反映DataFrame中行的新位置。我想仍然能够按照原始索引定位任何一行。

例如:
这是在删除第0和第2行之前和之后的情况。

之前:
在删除 pandas DataFrame 行之后,如何仍然通过相同的索引定位一行?

之后:
在删除 pandas DataFrame 行之后,如何仍然通过相同的索引定位一行?

当我尝试使用索引1来定位行时,我得到以下结果:
在删除 pandas DataFrame 行之后,如何仍然通过相同的索引定位一行?

如何仍然能够获取索引为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:

在删除 pandas DataFrame 行之后,如何仍然通过相同的索引定位一行?

after:

在删除 pandas DataFrame 行之后,如何仍然通过相同的索引定位一行?

and this is what I get when I locate the row with index 1:

在删除 pandas DataFrame 行之后,如何仍然通过相同的索引定位一行?

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],:]

huangapple
  • 本文由 发表于 2023年4月4日 08:12:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定