首页 > 解决方案 > 如何在没有嵌套 for 循环的情况下遍历数据框?

问题描述

如何在不嵌套 for 循环的情况下遍历 pandas 中的数据框?

我的代码是:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]],columns=['a','b','c'])

标签: pandas

解决方案


也许您想尝试使用此方法遍历每一行和每一列。

print([df.loc[row, col] for row in df.index for col in df.columns])

这输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

推荐阅读