Python添加匹配行值的新列?解决df.loc报错'int'无loc属性问题
解决方法:'int' object has no attribute 'loc' 错误
错误原因
这个错误说明你的变量 df 不是 pandas DataFrame 对象,而是被意外赋值成了整数。你需要先确保 df 正确初始化为包含表格数据的 DataFrame,再使用 .loc 方法。
步骤1:正确初始化 DataFrame
首先将你的表格数据转换成 pandas DataFrame:
import pandas as pd # 初始化表格数据 data = [ ["Product 1", "x", "xx"], ["Product 2", "a", "aa"], ["Product 3", "b", "bb"], ["Product 4", "c", "cc"], ["Product 5", "y", "y"] ] # 创建 DataFrame df = pd.DataFrame(data, columns=["Name", "Col1", "Col2"])
步骤2:添加 Col3 列并赋值
有两种常用方法可以为不同产品设置特定值:
方法1:使用 .loc 逐个赋值
先初始化 Col3 列,再通过条件匹配赋值:
# 初始化 Col3 为缺失值(避免列不存在的问题) df["Col3"] = pd.NA # 为每个产品设置对应值 df.loc[df["Name"] == "Product 1", "Col3"] = 100 df.loc[df["Name"] == "Product 2", "Col3"] = 40 df.loc[df["Name"] == "Product 3", "Col3"] = 200 # 替换为你的实际值 df.loc[df["Name"] == "Product 4", "Col3"] = 50 # 替换为你的实际值 df.loc[df["Name"] == "Product 5", "Col3"] = 1000
方法2:使用映射字典(更简洁高效)
创建产品与值的映射关系,一次性完成赋值:
# 定义产品到 Col3 值的映射 col3_mapping = { "Product 1": 100, "Product 2": 40, "Product 3": 200, "Product 4": 50, "Product 5": 1000 } # 生成 Col3 列 df["Col3"] = df["Name"].map(col3_mapping)
验证结果
执行上述代码后,你的 DataFrame 将变为预期格式:
| Name | Col1 | Col2 | Col3 | |------------|------|------|------| | Product 1 | x | xx | 100 | | Product 2 | a | aa | 40 | | Product 3 | b | bb | 200 | | Product 4 | c | cc | 50 | | Product 5 | y | y | 1000 |
内容的提问来源于stack exchange,提问作者tran su
相关产品推荐
相关产品推荐

