Home >Backend Development >Python Tutorial >How Do I Set a Specific Cell Value in a Pandas DataFrame?

How Do I Set a Specific Cell Value in a Pandas DataFrame?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 22:24:14222browse

How Do I Set a Specific Cell Value in a Pandas DataFrame?

Setting a Value for a Specific Cell in a Pandas DataFrame

When working with a Pandas DataFrame, it is often necessary to assign a value to a specific cell. While the df.xs() method allows you to select a row, it creates a copy of the data, preventing modifications to the original DataFrame.

To correctly modify the DataFrame, use df.at['C', 'x'], where 'C' is the row index and 'x' is the column name. This alternative directly accesses the desired cell and assigns the provided value.

For instance, consider the following DataFrame:

import pandas as pd
df = pd.DataFrame(index=['A','B','C'], columns=['x','y'])

To assign '10' to the cell in row 'C' and column 'x', use:

df.at['C', 'x'] = 10

This code directly modifies the original DataFrame, and the resulting DataFrame will look like:

     x    y
A  NaN  NaN
B  NaN  NaN
C   10  NaN

Note that while 'set_value' has been suggested as an alternative, it is slated for deprecation. Therefore, it is recommended to use 'at' or 'iat' for accessing and modifying specific cell values in Pandas DataFrames.

The above is the detailed content of How Do I Set a Specific Cell Value in a Pandas DataFrame?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn