pandas DataFrame 中每一行的操作

use*_*659 7 python dataframe pandas

我想遍历 Pandas DataFrame 中的每一行,并对每一行中的元素做一些事情。

现在我有

for row in df.iterrows(): 
    if row['col'] > 1.5:
        doSomething
Run Code Online (Sandbox Code Playgroud)

但它告诉我 '元组索引必须是整数,而不是 str' 。如何访问特定行中所需的列?

gus*_*coh 8

您可以将apply函数与选项一起使用axis=1。例如:

def my_function(row):
    if row['col'] > 1.5:
        doSomething()
    else:
        doSomethingElse()

my_df.apply(my_function, axis=1)
Run Code Online (Sandbox Code Playgroud)

来源

  • 这是最好的答案。因为它是最有效率的。使用for循环需要更多时间。使用向量函数而不是 for 循环需要更少的计算时间。观看 Udacity 的这个[视频](https://youtu.be/WF9n_19V08g),了解如何使用 pandas 和 NumPy 的矢量函数优化代码。https://youtu.be/WF9n_19V08g (2认同)

Pro*_*ggi 5

可能最简单的解决方案是使用APPLYMAPAPPLY函数,将函数应用于整个数据集中的每个数据值。

您可以通过以下几种方式执行此操作:

df.applymap(someFunction)
Run Code Online (Sandbox Code Playgroud)

或者

df[["YourColumns"]].apply(someFunction)
Run Code Online (Sandbox Code Playgroud)

链接如下:

应用地图文档

应用文档


unu*_*tbu 4

iterrows收益率(指数,系列)对。因此,使用:

for index, row in df.iterrows(): 
    if row['col'] > 1.5:
        doSomething
Run Code Online (Sandbox Code Playgroud)

但请注意,DataFrame 主要是基于列的数据结构,因此如果您可以围绕按列操作而不是按行操作构建代码,您将获得更好的性能。