简体   繁体   English

pandas DataFrame中每一行的操作

[英]Operations on every row in pandas DataFrame

I want to iterate through every row in a pandas DataFrame, and do something with the elements in each row. 我想迭代pandas DataFrame中的每一行,并对每行中的元素做一些事情。

Right now I have 现在我有

for row in df.iterrows(): 
    if row['col'] > 1.5:
        doSomething

but it tells me that the 'tuple indices must be integers, not str' . 但它告诉我'元组索引必须是整数,而不是str'。 How do I access the column that I want in a certain row? 如何在特定行中访问我想要的列?

iterrows yields (index, Series) pairs. iterrows yield(index,Series)对。 Therefore, use: 因此,使用:

for index, row in df.iterrows(): 
    if row['col'] > 1.5:
        doSomething

Note, however, that a DataFrame is a primarily column-based data structure , so you'll get better performance if you can structure your code around column-wise operations, instead of row-wise operations. 但请注意, DataFrame是一个主要基于列的数据结构 ,因此如果您可以围绕逐列操作而不是逐行操作来构建代码,那么您将获得更好的性能。

Probably the simplest solution is to use the APPLYMAP or APPLY fucntions which applies the function to every data value in the entire data set. 可能最简单的解决方案是使用APPLYMAPAPPLY函数将函数应用于整个数据集中的每个数据值。

You can execute this in a few ways: 您可以通过以下几种方式执行此操作:

df.applymap(someFunction)

or 要么

df[["YourColumns"]].apply(someFunction)

The Links are below: 链接如下:

ApplyMap Docs ApplyMap文档

Apply Docs 申请文件

You can use apply function with option axis=1 . 您可以使用选项axis=1 apply函数。 For example: 例如:

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

my_df.apply(my_function, axis=1)

source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM