【问题标题】:How to skip some symbol characters, when this character is used as a split column symbol in pandas split function如何跳过一些符号字符,当此字符用作熊猫拆分功能中的拆分列符号时
【发布时间】:2022-01-20 02:12:03
【问题描述】:

我有一个如下的数据框: Original data

index   string
0        a,b,c,d,e,f
1        a,b,c,d,e,f
2        a,(I,j,k),c,d,e,f

我想成为: To be data

index   col1    col2    col3    col4    col5    col6
0        a       b       c       d       e        f
1        a       b       c       d       e        f
2        a     (I,j,k)   c       d       e        f

【问题讨论】:

    标签: python pandas dataframe split


    【解决方案1】:

    您可以使用不在括号内的逗号进行拆分。然后将结果转换为 DataFrame 并分配给df 列:

    df[['col {}'.format(i) for i in range(1,7)]] =  df['string'].str.split(r",\s*(?![^()]*\))").apply(pd.Series)
    

    输出:

       index             string col 1    col 2 col 3 col 4 col 5 col 6
    0      0        a,b,c,d,e,f     a        b     c     d     e     f
    1      1        a,b,c,d,e,f     a        b     c     d     e     f
    2      2  a,(I,j,k),c,d,e,f     a  (I,j,k)     c     d     e     f
    

    【讨论】:

    • 为我打开一个新世界。非常感谢。
    【解决方案2】:

    试试这个:

    df = df['string'].str.split(r",\s*(?![^()]*\))", expand= True)
    df.columns = ['col1','col2','col3','col4','col5','col6']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 2022-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多