Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a value in a pandas DataFrame by mixed iloc and loc

Tags:

python

pandas

Say I want a function that changes the value of a named column in a given row number of a DataFrame.
One option is to find the column's location and use iloc, like that:

def ChangeValue(df, rowNumber, fieldName, newValue):
    columnNumber = df.columns.get_loc(fieldName)
    df.iloc[rowNumber, columnNumber] = newValue

But I wonder if there is a way to use the magic of iloc and loc in one go, and skip the manual conversion.

Any ideas?

like image 428
Paul Oyster Avatar asked Aug 27 '15 20:08

Paul Oyster


People also ask

Can you use ILOC and LOC together?

loc and iloc are interchangeable when labels are 0-based integers.

How do I change values in ILOC?

Using iloc() method to update the value of a row With the Python iloc() method, it is possible to change or update the value of a row/column by providing the index values of the same. In this example, we have updated the value of the rows 0, 1, 3 and 6 with respect to the first column i.e. 'Num' to 100.


1 Answers

I suggest just using iloc combined with the Index.get_loc method. eg:

df.iloc[0:10, df.columns.get_loc('column_name')]

A bit clumsy, but simple enough.

MultiIndex has both get_loc and get_locs which takes a sequence; unfortunately Index just seems to have the former.

like image 199
travc Avatar answered Sep 17 '22 09:09

travc