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
?
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.
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.
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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With