how to change a particular row in a dataframe in python

To change a particular row in a dataframe in Python using the pandas library, you can use the loc or iloc accessor.

Here's an example showing how to change a row based on a particular index using the loc accessor:

main.py
import pandas as pd

# Create a sample dataframe
data = {'Name': ['John', 'Emma', 'Jack', 'Sophia'],
        'Age': [25, 28, 30, 26],
        'City': ['New York', 'London', 'Paris', 'Sydney']}
df = pd.DataFrame(data)

# Print the original dataframe
print("Original DataFrame:")
print(df)

# Change the values of the row with index 1
df.loc[1] = ['Adam', 32, 'Berlin']

# Print the modified dataframe
print("\nModified DataFrame:")
print(df)
441 chars
19 lines

Output:

main.py
Original DataFrame:
    Name  Age      City
0   John   25  New York
1   Emma   28    London
2   Jack   30     Paris
3  Sophia   26    Sydney

Modified DataFrame:
    Name  Age      City
0   John   25  New York
1   Adam   32    Berlin
2   Jack   30     Paris
3  Sophia   26    Sydney
283 chars
14 lines

In this example, we use the loc indexer to specify the row with index 1 and assign a new list of values to replace the existing row values.

You can also use the iloc accessor to change a row based on its integer position:

main.py
# Change the values of the row with integer position 2
df.iloc[2] = ['Max', 33, 'Tokyo']
89 chars
3 lines

Both loc and iloc provide powerful ways to access and modify data in a dataframe based on labels or integer positions. Remember to provide the correct index or position to change the desired row.

gistlibby LogSnag