【问题标题】:Convert a column of json strings into columns of data将一列json字符串转换成数据列
【发布时间】:2018-11-12 08:46:40
【问题描述】:

我有一个大约 30000 行的大数据框和一个包含 json 字符串的单列。每个 json 字符串包含许多变量及其值我想将此 json 字符串分解为数据列

两行看起来像

0 {"a":"1","b":"2","c":"3"}
1 {"a" ;"4","b":"5","c":"6"}

我想把它转换成类似的数据框

a   b   c
1   2   3
4   5   6

请帮忙

【问题讨论】:

    标签: python json pandas dataframe


    【解决方案1】:
    with open(json_file) as f:
        df = pd.DataFrame(json.loads(line) for line in f)
    

    【讨论】:

      【解决方案2】:

      您的列值似乎在实际 json 字符串之前有一个额外的数字。所以你可能想先把它去掉(如果不是这样,请跳到 Method

      一种方法是将函数应用于列

      # constructing the df
      df = pd.DataFrame([['0 {"a":"1","b":"2","c":"3"}'],['1 {"a" :"4","b":"5","c":"6"}']], columns=['json'])
      
      # print(df)
                               json
      # 0  0 {"a":"1","b":"2","c":"3"}
      # 1  1 {"a" :"4","b":"5","c":"6"}
      
      # function to remove the number
      import re
      
      def split_num(val):
          p = re.compile("({.*)")
          return p.search(val).group(1)
      
      # applying the function
      df['json'] = df['json'].map(lambda x: split_num(x))
      print(df)
      
      #                          json
      # 0   {"a":"1","b":"2","c":"3"}
      # 1  {"a" :"4","b":"5","c":"6"}
      

      方法:

      一旦df 采用上述格式,下面就会将每一行条目转换为字典:

      df['json'] = df['json'].map(lambda x: dict(eval(x)))
      

      然后,将pd.Series 应用于列即可完成工作

      d = df['json'].apply(pd.Series)
      print(d)
      #   a  b  c
      # 0  1  2  3
      # 1  4  5  6
      

      【讨论】:

        猜你喜欢
        • 2020-06-30
        • 2018-07-26
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        相关资源
        最近更新 更多