python - pandas 使用 .loc 对多列进行条件赋值

标签 python pandas dataframe

使用pandas版本1.0.5

我有以下数据框:

test = {'Price': ['Free','free', '-16.66', 'Name', '']}
df = pd.DataFrame(test)
df.loc[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

在这个例子中如果 value 包含 : 那么我需要拆分这些值,并需要将两部分分别分配给两个新的列 col_1col_2

但我收到此错误:

KeyError: "None of [Index(['col_1', 'col_2'], dtype='object')] are in the [columns]"

我在这里缺少什么?

编辑:我尝试不使用 .loc

df[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

并收到此错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

最佳答案

如果不可能升级,请创建具有空值的列:

df = df.assign(col_1=np.nan, col_2=np.nan)

df.loc[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

另一个想法,感谢 @azro 为我工作,如果至少有一个值带有 ::

df[['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

关于python - pandas 使用 .loc 对多列进行条件赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70107277/

相关文章:

r - 在 R 中制作 "dropdown"函数

python - 使用多个子模板构建 jinja/flask 模板?

python - 从特定索引向数据框添加新值?

pandas - 获取 Pandas 数据框的多列(笛卡尔积)的组合?

python - 降维后使用选定的变量会引发值错误

将值替换为另一个数据帧的值

python - pandas 从累积的多类别列中计算每日总计

python - 如何使用 7zip 而不是 zip 进行压缩,更改代码

python - py2neo ogm 与多个节点标签的关系

python - 线程错误无法启动新线程