3

I am new to python panda, I am trying to read an excel file and do some calculations and fill up some rows. When I try to fill up the value and print the result, the results is still the same before I assign the value to it.

Here is what I did.

df.loc[1][13] = 2

df is just what I got from my excel file like this

df = pd.read_excel('test.xlsx',header=5)

I already checked the data in df, they are perfectly fine.

so the original value in row 1, column 13 is nan, I want to replace it with a number, such as a 2, but the code above just would not work.

3

2 Answers 2

2

As mentioned in this doc https://pandas.pydata.org/pandas-docs/version/0.23/10min.html#selection-by-position, .loc method provides selection by label whereas .iloc method provides selection by position. Also, since output of your selection is scalar you can also use .iat method. So, either of the below will work in your case:

df.iloc[1, 13] = 2 
df.iat[1,13] = 2

In general, I prefer to use one of the .loc or .iloc depending upon whether the selection is by label or by position.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This is really helpful
It would be really nice if you accept this answer too.
1

check out the pandas documentation for iloc

Based on that a very simple example for replacing specifically the value in one given cell could look like this:

import pandas as pd
mydict = [{'a': 1, 'b': 2, 'c': 3, 'd': 4},\
          {'a': 100, 'b': 200, 'c': 300, 'd': 400},\
          {'a': 1000, 'b': 2000, 'c': 3000, 'd': 4000 }]
df = pd.DataFrame(mydict)

print(df.iloc[0,2]) # print original value from row 0, column 2
df.iloc[0,2] = 9 # replace value in row 0, column 2
print(df.iloc[0,2]) #verify replaced value in row 0, column 2

Hope I got the question right...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.