如何在 Pandas DataFrame 中设置单元格值?
在本文中,我们将讨论如何在Python中设置 Pandas DataFrame 中的单元格值。
方法一:使用 pandas.dataframe.at 方法
此方法用于为现有值设置值或设置新记录。
语法:
dataframe.at[index, 'column_name'] = value
在哪里,
- 数据框是输入数据框
- index 是要插入的位置
- column_name 是插入值的列
- value 是要插入的值
示例:
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 3 rows amd 3 columns
data = pd.DataFrame({
'name': ['sireesha', 'ravi', 'rohith', 'pinkey', 'gnanesh'],
'subjects': ['java', 'php', 'html/css', 'python', 'R'],
'marks': [98, 90, 78, 91, 87]
})
# set value at 6 th location for name column
data.at[5, 'name'] = 'sri devi'
# set value at 6 th location for subjects column
data.at[5, 'subjects'] = 'jsp'
# set value at 6 th location for marks column
data.at[5, 'marks'] = 100
# set value at 4 th location for name column
data.at[4, 'name'] = 'siva nagulu'
# set value at 4 th location for subjects column
data.at[4, 'subjects'] = 'react-js'
# set value at 4 th location for marks column
data.at[4, 'marks'] = 80
# display
data
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 3 rows amd 3 columns
data = pd.DataFrame({
'name': ['sireesha', 'ravi', 'rohith', 'pinkey', 'gnanesh'],
'subjects': ['java', 'php', 'html/css', 'python', 'R'],
'marks': [98, 90, 78, 91, 87]
})
# set value at 6 th location for name column
data.loc[5, 'name'] = 'sri devi'
# set value at 6 th location for subjects column
data.loc[5, 'subjects'] = 'jsp'
# set value at 6 th location for marks column
data.loc[5, 'marks'] = 100
# set value at 4 th location for name column
data.loc[4, 'name'] = 'siva nagulu'
# set value at 4 th location for subjects column
data.loc[4, 'subjects'] = 'react-js'
# set value at 4 th location for marks column
data.loc[4, 'marks'] = 80
# display
data
输出:
方法二:使用 loc() 方法
这里我们使用 loc() 方法根据行索引和列名设置列值
语法:
dataframe.loc[index, 'column_name'] = value
在哪里,
- 数据框是输入数据框
- index 是要插入的位置
- column_name 是插入值的列
- value 是要插入的值
示例:
Python3
# import pandas module
import pandas as pd
# create a dataframe
# with 3 rows amd 3 columns
data = pd.DataFrame({
'name': ['sireesha', 'ravi', 'rohith', 'pinkey', 'gnanesh'],
'subjects': ['java', 'php', 'html/css', 'python', 'R'],
'marks': [98, 90, 78, 91, 87]
})
# set value at 6 th location for name column
data.loc[5, 'name'] = 'sri devi'
# set value at 6 th location for subjects column
data.loc[5, 'subjects'] = 'jsp'
# set value at 6 th location for marks column
data.loc[5, 'marks'] = 100
# set value at 4 th location for name column
data.loc[4, 'name'] = 'siva nagulu'
# set value at 4 th location for subjects column
data.loc[4, 'subjects'] = 'react-js'
# set value at 4 th location for marks column
data.loc[4, 'marks'] = 80
# display
data
输出: