繁体   English   中英

pandas 使用.loc 对多列进行条件分配

[英]pandas conditional assignment to multiple columns using .loc

使用 pandas 版本1.0.5

我有以下 dataframe:

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)

例如,如果值包含:那么我需要拆分值并需要将两个部分分别分配给两个新的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)

看一下这个:)

test = {'Price': ['Free','free', '-16.66', 'Name', '', "what:yes"]}
df = pd.DataFrame(test)
df[['one', 'two']] = df['Price'].astype(str).str.split(':',1,expand = True)
df.fillna('')

Output:

    Price       one     two
0   Free        Free    
1   free        free    
2   -16.66      -16.66  
3   Name        Name    
4           
5   what:yes    what    yes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM