Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。
Pandas dataframe.set_value()函数将单个值放在传递的列和索引处。它以轴标签为输入,并以标量值放置在 DataFrame 中的指定索引处。替代此功能的是.at[]或者.iat[]。
用法:DataFrame.set_value(index, col, value, takeable=False)
参数:
index: row label
col: column label
value: scalar value
takeable: interpret the index/col as indexers, default False
返回:frame:DataFrame如果包含标签对,将引用调用DataFrame,否则将引用一个新对象
范例1:采用set_value()函数将数据帧中的值设置为特定索引。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 5, 3, 4, 2],
"B":[3, 2, 4, 3, 4],
"C":[2, 2, 7, 3, 4],
"D":[4, 3, 6, 12, 7]})
# Print the dataframe
df
让我们使用dataframe.set_value()用于设置特定索引值的函数。
# set value of a cell which has index label "2" and column label "B"
df.set_value(2, 'B', 100)
输出:
范例2:采用set_value()用于设置 DataFrame 中不存在的索引和列的值的函数。
# importing pandas as pd
import pandas as pd
# Creating the dataframe
df = pd.DataFrame({"A":[1, 5, 3, 4, 2],
"B":[3, 2, 4, 3, 4],
"C":[2, 2, 7, 3, 4],
"D":[4, 3, 6, 12, 7]})
# Print the dataframe
df
让我们使用dataframe.set_value()用于设置特定索引值的函数。
# set value of a cell which has index label "8" and column label "8"
df.set_value(8, 8, 1000)
输出:
请注意,对于 DataFrame 中不存在的行和列,已插入新的行和列。