重新索引从DataFrame提取的大熊猫系列



有问题的

让我们说我有这样的n行数据框架:

|降水|排放|
|:------ 12 --------:|:------ 16 -----:|
|:------ 10 --------:|:----- 15 -----:|
|:------ 12 --------:|:------ 16 -----:|
|:------ 10 --------:|:----- 15 -----:|
...
|:------ 12 --------:|:------ 16 -----:|
|:------ 10 -------:|:------ 15 -----:|

行自动从1到n索引。例如,当我们提取一列时:

series = df.loc[5:,['Precipitation']]
or
series = df.Precipitation[5:]

提取的系列倾向于:
   nbsp; nbsp;降水
5 16
6 17
7 18
...
n 15

因此,问题是我们如何将通用索引从5到N到0更改为N-5。

请注意,我尝试了series.reindex((和series.reset_index((,但它们俩都没有工作...
目前,我做series.tolist((解决问题,但是有什么方法更优雅,更聪明?

非常感谢!

如果我正确理解您的问题,您想选择列的第一个N-5行。

import pandas as pd
df = pd.DataFrame({'col1': [1,2,3,4,5,6,7], 'col2': [3,4,3,2,5,9,7]})
df.loc[:len(df)-5,['col1']]

您可能想与大熊猫进行切片:https://pandas.pydata.org/pandas-docs/stable/indexing.html#slicing-ranges

编辑:

我认为我误解了,而您想要的是"重置"您的索引。您可以使用方法reset_index((

做到这一点
import pandas as pd
df = pd.DataFrame({'col1': [1,2,3,4,5,6,7], 'col2': [3,4,3,2,5,9,7]})
df = df.loc[5:,['col1']]
df.reset_index(drop=True)

最新更新