【问题标题】:Pandas, DataFrame: Splitting one column into multiple columnsPandas,DataFrame:将一列拆分为多列
【发布时间】:2016-11-17 22:59:07
【问题描述】:

我有以下数据框。我想知道是否可以将data 列分成多列。例如,从此:

身份证日期数据 6 2016 年 5 月 21 日 A:7,B:8,C:5,D:5,A:8 6 2014 年 1 月 21 日 B:5,C:5,D:7 6 2013 年 2 月 4 日 A:4,D:7 7 05/06/2014 C: 25 7 2014 年 12 月 8 日 日:20 8 2012 年 4 月 18 日 A:2,B:3,C:3,E:5,B:4 8 2012 年 3 月 21 日 F:6,B:4,F:5,D:6,B:4

进入这个:

ID 日期数据 A B C D E F 6 2016 年 5 月 21 日 A:7,B:8,C:5,D:5,A:8 15 8 5 5 0 0 6 2014 年 1 月 21 日 B:5,C:5,D:7 0 5 5 7 0 0 6 02/04/2013 B:4,D:7,B:6 0 10 0 7 0 0 7 05/06/2014 C: 25 0 0 25 0 0 0 7 2014 年 8 月 12 日 D:20 0 0 0 20 0 0 8 2012 年 4 月 18 日 A:2,B:3,C:3,E:5,B:4 2 7 3 0 5 0 8 21/03/2012 F:6,B:4,F:5,D:6,B:4 0 8 0 6 0 11

我已经尝试过这个Split strings in tuples into columns, in Pandas 和这个pandas: How do I split text in a column into multiple rows?,但它们在我的情况下不起作用。

编辑

data 列具有重复值有点复杂,例如第一行 A 重复,因此这些值在 A 列下汇总(请参阅第二个表)。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这里有一个函数,可以将字符串转换为字典,并根据键聚合值;转换后使用pd.Series方法很容易得到结果:

    def str_to_dict(str1):
        import re
        from collections import defaultdict
        d = defaultdict(int)
        for k, v in zip(re.findall('[A-Z]', str1), re.findall('\d+', str1)):
            d[k] += int(v)
        return d
    
    pd.concat([df, df['dictionary'].apply(str_to_dict).apply(pd.Series).fillna(0).astype(int)], axis=1)
    

    【讨论】:

      【解决方案2】:
      df = pd.DataFrame([
              [6, "a: 1, b: 2"],
              [6, "a: 1, b: 2"],
              [6, "a: 1, b: 2"],
              [6, "a: 1, b: 2"],
          ], columns=['ID', 'dictionary'])
      
      def str2dict(s):
          split = s.strip().split(',')
          d = {}
          for pair in split:
              k, v = [_.strip() for _ in pair.split(':')]
              d[k] = v
          return d
      
      df.dictionary.apply(str2dict).apply(pd.Series)
      

      或者:

      pd.concat([df, df.dictionary.apply(str2dict).apply(pd.Series)], axis=1)
      

      【讨论】:

      • 这只会给你一个系列,不会分成多列。
      • @user1124825 我编辑了答案以包含一个字符串解析器。您最初的问题提到标记为'dictionary' 的列是一列字典。我以为那是真的。通过应用解析器,我的答案仍然成立。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 2022-12-29
      • 1970-01-01
      • 2019-05-18
      • 2022-01-03
      相关资源
      最近更新 更多