Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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' . How do I access the column that I want in a certain row?

like image 784
user3264659 Avatar asked Oct 07 '14 19:10

user3264659


People also ask

Is each row in a DataFrame a Series?

Each column in a DataFrame is a Series A pandas Series has no column labels, as it is just a single column of a DataFrame . A Series does have row labels.

How do you get all the rows in pandas?

Method 2: Using set_option() A function set_option() is provided by pandas to display all rows of the data frame. display. max_rows represents the maximum number of rows that pandas will display while displaying a data frame. The default value of max_rows is 10.

How do I apply a function to all columns in pandas?

Use apply() to Apply Functions to Columns in Pandas The apply() method allows to apply a function for a whole DataFrame, either across columns or rows. We set the parameter axis as 0 for rows and 1 for columns. The new appended e column is the sum of data in column a and b .


2 Answers

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.

You can execute this in a few ways:

df.applymap(someFunction)

or

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

The Links are below:

ApplyMap Docs

Apply Docs

like image 194
ProfVersaggi Avatar answered Oct 23 '22 14:10

ProfVersaggi


You can use apply function with option axis=1. For example:

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

my_df.apply(my_function, axis=1)

source

like image 38
gustavovelascoh Avatar answered Oct 23 '22 15:10

gustavovelascoh