How can we edit specific cell data in pandas?

To modify a specific cell data in a Pandas DataFrame, you can use the .at or .iat or .loc or .iloc attribute. Here are examples of using these attributes:

  1. With the use of the .at attribute, you can locate a cell using row and column labels and then set a new value. For example:
import pandas as pd

# 创建DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# 使用 .at 设置指定单元格的值
df.at[0, 'A'] = 10

print(df)

Output result:

    A  B  C
0  10  4  7
1   2  5  8
2   3  6  9
  1. By using the .loc attribute, you can locate a specific cell by row index and column label, and then set a new value. For example:
import pandas as pd

# 创建DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# 使用 .loc 设置指定单元格的值
df.loc[0, 'A'] = 10

print(df)

The output result is the same as the example above.

  1. With the .iat attribute, you can use row and column indices to locate a cell and assign a new value. For example:
import pandas as pd

# 创建DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# 使用 .iat 设置指定单元格的值
df.iat[0, 0] = 10

print(df)

The output is the same as the example above.

  1. You can use the .iloc attribute to locate a cell by integer position of row and column indices, and update its value. For example:
import pandas as pd

# 创建DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})

# 使用 .iloc 设置指定单元格的值
df.iloc[0, 0] = 10

print(df)

The output result is the same as the example mentioned above.

You can modify the data of specified cells as needed using any method.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds