【问题标题】:Pandas df split values out from one column into their own columnsPandas df 将值从一列拆分为自己的列
【发布时间】:2018-03-30 18:44:21
【问题描述】:

如何使用 Pandas 和 Python 做到这一点?我正在使用 Jupyter Notebook。

我有一个这样的数据框:

    col
0   2017 / something
1   $5.91 (× 1)
2   Premium
3   2017 / anotherthing
4   $16.0 (× 1)
5   Business

我想将那里的值拆分为自己的列,如下所示:

    col                    revenue        plan
0   2017 / something       $5.91 (× 1)    Premium
1   2017 / anotherthing    $16.0 (× 1)    Business

然后从收入列中删除括号值和美元符号,因此我最终得到以下结果:

    col                    revenue     plan
0   2017 / something       5.91        Premium
1   2017 / anotherthing    16.0        Business

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    In [113]: (df[['col']].replace(r'\s*\([^\)]*\)', '', regex=True)
         ...:             .set_index(np.arange(len(df))//3)
         ...:             .set_index(np.arange(len(df))%3, append=True)['col']
         ...:             .unstack())
         ...:
    Out[113]:
                         0      1         2
    0     2017 / something  $5.91   Premium
    1  2017 / anotherthing  $16.0  Business
    

    【讨论】:

      【解决方案2】:

      使用pd.MultiIndex.from_arrays__divmod__
      我们使用 3 的值,因为我们想要得到 3 列。

      d = df.set_index(
          pd.MultiIndex.from_arrays(np.arange(len(df)).__divmod__(3))
      ).col.unstack().rename(columns={0: 'col', 1: 'revenue', 2: 'plan'})
      
      d.assign(revenue=d.revenue.str.extract('\$(.*) \(', expand=False))
      
                         col revenue      plan
      0     2017 / something    5.91   Premium
      1  2017 / anotherthing    16.0  Business
      

      【讨论】:

        【解决方案3】:

        改编其他部分解决方案以使用更清洁的解决方案组合来获得操作请求的输出。

        # make dataframe 
        df = pd.DataFrame(columns=['col'], data=['2017 / something', '$5.91 (× 1)', 'Premium', '2017 / anotherthing', '$16.0 (× 1)', 'Business'])
        
        # break into 3 columns(per piRSquared's solution) and rename
        df = df.set_index(
            pd.MultiIndex.from_arrays(np.arange(len(df)).__divmod__(3))
            ).col.unstack().rename(columns={0: 'col', 1: 'revenue', 2: 'plan'})
        
        # strip parenthesis values and dollar signs
        df.revenue = df.revenue.replace(r'\s*\([^\)]*\)', '', regex=True).str.strip('$')
        print(df)
        

        输出:

                           col revenue      plan
        0     2017 / something    5.91   Premium
        1  2017 / anotherthing    16.0  Business
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-04-10
          • 1970-01-01
          • 2017-03-31
          • 2020-08-16
          • 2022-11-29
          • 1970-01-01
          • 2016-11-17
          相关资源
          最近更新 更多