如何基于另外两列值修改Pandas DataFrame列值
解决方案
可以通过分步定位行范围来避免结果互相覆盖,核心思路是先初始化新列为缺失值,再针对不同条件的行分别赋值,确保只修改目标行:
示例代码
import pandas as pd import numpy as np # 构造你的示例数据 data = { "component": ["class", "property", "instance", "property", "property", "property", "instance", "class"], "rdfs:range": [np.nan, "xsd:int", np.nan, "obj:ObjectName", "xsd:string", "obj:Object2Name", np.nan, np.nan] } sample_df = pd.DataFrame(data) # 定义data property对应的字典(替换成你实际的字典) data_property_dict = { "xsd:int": "data property", "xsd:string": "data property" } # 1. 初始化subcomponent列为缺失值(对应需求1:class/instance默认保持NaN) sample_df["subcomponent"] = pd.NA # 2. 匹配data property字典,仅对component为property的行生效 is_property = sample_df["component"] == "property" sample_df.loc[is_property, "subcomponent"] = sample_df.loc[is_property, "rdfs:range"].map(data_property_dict) # 3. 对未匹配字典的property行,设置为object property is_unmatched_property = is_property & sample_df["subcomponent"].isna() sample_df.loc[is_unmatched_property, "subcomponent"] = "object property"
逻辑说明
- 先初始化新列为
pd.NA,确保class/instance类型的行默认保持缺失值,不会被后续操作覆盖。 - 用
loc定位仅component为property的行,通过map匹配字典赋值data property,只修改目标行。 - 最后筛选出
property类型且subcomponent仍为缺失值的行,统一设置为object property,完美覆盖未匹配的情况。
运行后得到的结果完全符合你的期望输出。
内容的提问来源于stack exchange,提问作者user3684314
相关产品推荐
相关产品推荐

