這個問題在這里已經有了答案: Dataframe pandas split str (1 個回答) 9 小時前關閉。
我在 Python Pandas 中有資料框,如下所示:
col1
-------
XX - YTR
AA - BRa
Nar - Op1
基于“col1”中的值,我想通過“col1”中的單獨值創建2個新列,因此我需要有如下解決方案:
col1 | col2| col3
-----------------------
XX - YTR | XX | YTR
AA - BRa | AA | BRa
Nar - Op1 | Nar | Op1
我怎樣才能在 Python Pandas 中做到這一點?
uj5u.com熱心網友回復:
使用str.split:
df = df.join(df['col1'].str.split(' - ', expand=True) \
.rename(columns={0: 'col2', 1: 'col3'}))
print(df)
# Output:
col1 col2 col3
0 XX - YTR XX YTR
1 AA - BRa AA BRa
2 Nar - Op1 Nar Op1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376269.html
上一篇:如何修改apply和lambda函式以基于PythonPandas中的其他函式創建新列?
下一篇:使用Pandas拆分和選擇唯一行
