【问题标题】:Splitting a column in two while leaving the original将一列一分为二,同时保留原始列
【发布时间】:2021-02-09 23:07:19
【问题描述】:

我在 pandas 中有一个像这样格式化的数据框。

(df)
School ID      Column 1 
School 1       AD6000         
School 2       3000TO4000      
School 3       5000TO6000      
School 4       AC2000         
School 5       BB3300        
School 6       9000TO9900      
....

我想要做的就是将其中包含单词“TO”作为分隔符的列拆分为新 DF 中的两个新列,但每次我这样做时它也会编辑原始列 1。

(NewDF)
School ID      Column 1          Column 2     Column 3
School 1       AD6000            NaN          NaN
School 2       3000TO4000        3000         4000
School 3       5000TO6000        5000         6000
School 4       AC2000            NaN          NaN
School 5       BB3300            NaN          NaN
School 6       9000TO9900        9000         9900
....

这是我一直在尝试的代码。

NewDF = df1['Column 1']
NewDF[['Column 2', 'Column 3']] = df1['Column 1'].str.split('TO\s+', expand=True, n=1) 

虽然这会创建两个新列,但它只是将第 1 列中的信息放入第 2 列,而不拆分字符串。然后我尝试了

NewDF[['Column 2','Column 3']] = NewDF['Column 2'].str.split('TO',expand=True, n=1)

我收到错误“列必须与键长度相同”。

感谢您的帮助。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我会用.str.extract:

    df[['Column 2','Column 3']] = df['Column 1'].str.extract(r'(\d+)TO(\d+)')
    

    【讨论】:

    • 编辑:实际上,它将 NaN 留在了应该是数字的第 2 列和第 3 列中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多