python - 如何重新排序 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 行序列非常感谢!
解决方案
永远不要使用这种结构:
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
推荐阅读
- c# - 我怎样才能使重载更简单
- kotlin - 如何在 kotlin 的 mockitoDeepMock#someMethod() 中修复 NPE
- swift - Swift - ScrollView 中的 StackView 不滚动
- c# - 在保存到数据库之前将数据存储到变量
- javascript - 无法在浏览器上下载excel文件
- excel - Excel 自动绘制具体数据范围的图表
- cloud-foundry - https 在 swisscom CloudFoundry 上没有按预期工作
- scala - 运行 SANSA-Stack/SANSA-Examples 时无法初始化类 org.apache.jena.riot.system.RiotLib 错误
- javascript - 检查 Iframe 是否在其源中包含 youtube 链接?
- ruby-on-rails - 如何在 Ruby on Rails 中将经度和纬度转换为数组