【问题标题】:Transform json content in new columns在新列中转换 json 内容
【发布时间】:2020-05-24 23:28:14
【问题描述】:

我有一个带有semi structured data 的数据集,我需要将json 内的content 列转换为其他列。

数据:

    customer    flow    session timestamp               content
1   C1000   F1000   S2000   2019-12-16 13:59:58+00:00   {'name': ''}
2   C1000   F1000   S2000   2019-12-16 13:59:59+00:00   {'name': 'joao'}
4   C1000   F1000   S2000   2019-12-16 13:59:59+00:00   {'cpf': '733.600.420-26'}

想要的结果如下所示:

+--------+-----+-------+-------------------+-------------------+-----+--------------+------------------+
|customer|flow |session|first_answer_dt    |last_answer_dt     |name |cpf           |delivery_confirmed|
+--------+-----+-------+-------------------+-------------------+-----+--------------+------------------+
|C1000   |F1000|S1000  |2019-12-16T13:59:58|2019-12-16T14:00:01|maria|305.584.960-40|sim               |
|C1000   |F1000|S2000  |2019-12-16T13:59:59|2019-12-16T14:00:00|joao |733.600.420-26|não               |
+--------+-----+-------+-------------------+-------------------+-----+--------------+------------------+

我正在互联网上搜索,但很难找到解决此案例的方法。

【问题讨论】:

标签: python python-3.x pandas pyspark


【解决方案1】:

IIUC,你可以试试.joinpd.Series

#use eval if your json is a string.
df1 = df.join(df['content'].map(eval).apply(pd.Series)).drop('content',axis=1)
#or if not string
df1 = df.join(df['content'].apply(pd.Series)).drop('content',axis=1)
print(df1)
  customer   flow session                 timestamp  name             cpf
0    C1000  F1000   S2000 2019-12-16 13:59:58+00:00                   NaN
1    C1000  F1000   S2000 2019-12-16 13:59:59+00:00  joao             NaN
2    C1000  F1000   S2000 2019-12-16 13:59:59+00:00   NaN  733.600.420-26

【讨论】:

  • 嘿,谢谢。但是不明白eval的作用。
  • @RafaelLima 是将原始字符串转换为对象
  • 就我而言,此列是一个对象。客户对象流对象会话对象时间戳 datetime64[ns, UTC] 内容对象 dtype: object
猜你喜欢
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 2022-01-25
  • 2017-08-26
  • 2019-11-20
  • 2021-12-28
相关资源
最近更新 更多