Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas update dataframe row with new value

Tags:

python

pandas

I have a text file which has been read into pandas by df1 = pandas.read_csv(r'fruits.txt', sep=',')

    item  freshness
0   apple    2.2
1   pear     0.0

and a series of calculations that would yield the result of apple = 2.3

Is it possible to do a pandas.update so that I can update the value of freshness for apple in the dataframe to 2.3?

like image 692
jake wong Avatar asked Apr 10 '16 14:04

jake wong


People also ask

How do I assign a value to a row in pandas?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.

How do you update a data frame?

Pandas DataFrame update() Method The update() method updates a DataFrame with elements from another similar object (like another DataFrame). Note: this method does NOT return a new DataFrame. The updating is done to the original DataFrame.

How to update the value of a row in Python Dataframe?

Python loc() method can also be used to update the value of a row with respect to columns by providing the labels of the columns and the index of the rows. Syntax: dataframe.loc[row index,['column-names']] = value

How to update Dataframe columns in pandas?

Then there is a function in pandas that allows you to update the records of the column. The function is pandas.DataFrame.update (). It easily updates the columns or the column records. In the entire tutorial, you will know how to update dataframe in pandas with examples.

How do I change the value of a row in pandas?

Updating Row Values Like updating the columns, the row value updating is also very simple. You have to locate the row value first and then, you can update that row with new values. You can use the pandas loc function to locate the rows. We have located row number 3, which has the details of the fruit, Strawberry.

How to change the value of any string within a Dataframe?

Using Python replace () method, we can update or change the value of any string within a data frame. We need not provide the index or label values to it.


1 Answers

IIUC you need loc:

apple = 2.3

print df['item'] == 'apple'
0     True
1    False
Name: item, dtype: bool

df.loc[df['item'] == 'apple', 'freshness'] = apple
print df
    item  freshness
0  apple        2.3
1   pear        0.0
like image 89
jezrael Avatar answered Sep 28 '22 07:09

jezrael