首页 > 解决方案 > 如何重新排序 DataFrame 行序列

问题描述

我已经定义了一个数据集:

df=pd.DataFrame(list(xx))

然后,我根据性别过滤了一些数据。

df=df[df["sex"]=="1"]

那么我应该遍历所有数据。

row,col=df.shape
for i in range(row):
    print(df["name"][i])  # error

调试代码,发现“df”行索引是旧索引,因为删除了很多不符合条件的数据。比如df["sex"][1]==1就是删除,所以循环会除外。

如何重新排序 DataFrame 行序列非常感谢!

标签: pythonpandas

解决方案


永远不要使用这种结构:

for i in range(nrows):
    do_stuff(df[column][i])

这是低效的。您几乎不想在数据帧上使用 for 循环,但如果必须,请使用pd.Dataframe.itertuples

>>> df = pd.DataFrame({'a':[1,2,3],'b':[3,4,5]})
>>> for row in df.itertuples():
...     print("the index", row.Index)
...     print("sum of row", row.a + row.b)
...
the index 0
sum of row 4
the index 1
sum of row 6
the index 2
sum of row 8

请注意,现在索引是否更改并不重要:

>>> df = df.iloc[[2,0,1]]
>>> df
   a  b
2  3  5
0  1  3
1  2  4
>>> for row in df.itertuples():
...     print("the index", row.Index)
...     print("sum of row", row.a + row.b)
...
the index 2
sum of row 8
the index 0
sum of row 4
the index 1
sum of row 6

最后,你可以一直重置你的索引,假设:

>>> df.drop(0, axis=0, inplace=True)
>>> df
   a  b
2  3  5
1  2  4

现在,只需使用:

>>> df.reset_index()
   index  a  b
0      2  3  5
1      1  2  4

并使用该drop参数不包括旧索引作为列:

>>> df.reset_index(drop=True)
   a  b
0  3  5
1  2  4

推荐阅读