使用熊貓版本 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)
在這里,在此例如,如果值包含:然后我需要拆分的價值和需要來分配兩個部分組成兩個新的colscol_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
uj5u.com熱心網友回復:
如果不可能升級創建具有空值的列:
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)
uj5u.com熱心網友回復:
看一下這個 :)
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('')
輸出:
Price one two
0 Free Free
1 free free
2 -16.66 -16.66
3 Name Name
4
5 what:yes what yes
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366378.html
上一篇:在Pandas中創建和洗掉列
