【问题标题】:How to create 2 new columns based on values separated by "-" in first column in Python Pandas? [duplicate]如何根据 Python Pandas 第一列中由“-”分隔的值创建 2 个新列? [复制]
【发布时间】:2022-01-12 23:21:33
【问题描述】:

我在 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 中做到这一点?

【问题讨论】:

标签: python python-3.x pandas dataframe


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 2020-08-14
    • 2021-09-09
    • 1970-01-01
    • 2018-09-22
    • 2021-03-20
    • 2020-04-16
    • 2020-08-18
    • 2021-03-19
    相关资源
    最近更新 更多