modify specific values in a dataframe in python

To modify specific values in a Pandas DataFrame in Python, you can use the .loc method to locate the specific row and column where the value is located, and then assign the new value to that location.

Here's an example:

main.py
import pandas as pd

# create a new DataFrame
data = {'name': ['John', 'Mike', 'Sarah', 'Kate'], 'age': [25, 30, 29, 27], 'gender': ['M', 'M', 'F', 'F']}
df = pd.DataFrame(data)

# print the original DataFrame
print(df)

# modify the value in the 'gender' column of the second row
df.loc[1, 'gender'] = 'F'

# print the modified DataFrame
print(df)
349 chars
15 lines

Output:

main.py
   name  age gender
0  John   25      M
1  Mike   30      M
2  Sarah  29      F
3  Kate  27      F

   name  age gender
0  John   25      M
1  Mike   30      F
2  Sarah  29      F
3  Kate  27      F
199 chars
12 lines

gistlibby LogSnag