【问题标题】:How to retrieve certain keys and values from json format data present as a column in pandas dataframe如何从熊猫数据框中以列形式存在的json格式数据中检索某些键和值
【发布时间】:2020-01-28 11:33:30
【问题描述】:

我有一个如下所示的数据框(列名 - 日期、错误消息、消息)

data = """Date|Error|message
   26/11/19   |   unauthorized access | {"eventVersion":"1.05","userIdentity":"type":"IAMUser","principalId":"AIDAIETZDDDVS36MMCHPS","arn":"arn:aws:iam::819490967212:user/IAMAdmin","accountId":"819490967212","accessKeyId":"ASIA35TLXZ2WPIBTBWP2","userName":"IAMAdmin","sessionContext":{"sessionIssuer":{},"webIdFederationData":{},"attributes":{"mfaAuthenticated":"false","creationDate":"2019-12-19T03:14:04Z"}}"""

from io import StringIO
df = pd.read_csv(StringIO(data),sep='|)

print(df)
Date        Error   message
0   26/11/19    unauthorized access {"eventVersion":"1.05","userIdentity":"type":...

消息列的每一行都有类似json格式的数据。

如何从“消息”列中检索某些键及其各自的值("userName", "account ID"),以便这些键可以成为新列。

尝试使用 python 但检索失败

【问题讨论】:

  • 你的 json 无效,这一行 "userIdentity":"type":"IAMUser",
  • 你的json是这样的吗?它似乎不是有效的 json?

标签: python json pandas dataframe


【解决方案1】:
df['userName'] = df['message'].apply(lambda x: x.get('userName'))
df['account'] = df['message'].apply(lambda x: x.get('account'))

【讨论】:

    【解决方案2】:

    你可以使用 json 或熊猫

    import json
    #some JSON:
    x =  '{ "name":"John", "age":30, "city":"New York"}'
    
    # parse x:
    y = json.loads(x)
    
    
    
    # the result is a Python dictionary:
    print(y["age"])
    

    或者你可以使用 pandas.read_json() 它的工作方式相同,但您应该使用方向。在这里查看:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html

    【讨论】:

      猜你喜欢
      • 2017-08-25
      • 2023-03-14
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      相关资源
      最近更新 更多