使用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_1
和 col_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/