如何在pandas中更改包含字典的字符串?

huangapple go评论86阅读模式
英文:

How to change a string containing a dict in pandas?

问题

ID computed_data
0987 "{"Status":{"participate":14,"create":"10","activ":"0"},"rescount":22,"comcount":0,"partrate":0}"
4568 "{"Status":{"participate":49,"create":"40","activ":"27"},"rescount":22,"comcount":0,"partrate":73.47}"
1234 "{"Status":{"participate":3,"create":"3","activ":"1"},"comcount":0,"partrate":100,"rescount":42}"

我正在尝试访问并获取computed_data列中的值。当我使用eval()时,它可以在一个单元格上工作。

eval(df["computed_data"][0])

我尝试使用for循环一次更改所有值,并将每个字典存储在一个列表中:

data = []
for x, i in enumerate(df["computed_data"]):
    data.append(eval(df["computed_data"][x]))

但是我收到一个错误消息 "name "null" is not defined"。我检查了一下,我的df中没有空值,它的形状是3601。

有人有什么想法吗?谢谢。

英文:
ID computed_data
0987 "{"Status":{"participate":14,"create":"10","activ":"0"},"rescount":22,"comcount":0,"partrate":0}"
4568 "{"Status":{"participate":49,"create":"40","activ":"27"},"rescount":22,"comcount":0,"partrate":73.47}"
1234 "{"Status":{"participate":3,"create":"3","activ":"1"},"comcount":0,"partrate":100,"rescount":42}"

I am trying to access and get the values in the computed_data column. It works on one cell when I am using eval().

eval(df["computed_data][0])

I tried a for loop to change all values at once and stored every dict in a list :

data = []
for x, i in enumerate(df["Computed Data"]):
    data.append(eval(df["Computed Data"][x]))

But I got an error "name "null" is not defined". I checked and I have no null values in my df which shape is 3601.

does anyone has an idea ? Thank you

答案1

得分: 0

以下是用于将不可解析字符串转换为空字典的自定义函数的解决方案:

import ast

def f(x):
    try:
        return ast.literal_eval(x)
    except ValueError:
        return {}

df["Computed Data"] = df["Computed Data"].str.strip('""').apply(f)
英文:

Here is solution with custom function for convert not parseable strings to empty dictionaries:

import ast

def f(x):
    try:
        return ast.literal_eval(x)
    except ValueError:
        return {}
        
df["Computed Data"] = df[ "Computed Data"].str.strip('"').apply(f)

答案2

得分: 0

from ast import literal_eval

df['computed_data'] = df['computed_data'].str.strip('"').apply(literal_eval)

Output:

     ID                                     computed_data
0   987      {'Status': {'participate': 14, 'create': '10', 'activ': '0'}, 'rescount': 22, 'comcount': 0, 'partrate': 0}
1  4568  {'Status': {'participate': 49, 'create': '40', 'activ': '27'}, 'rescount': 22, 'comcount': 0, 'partrate': 73.47}
2  1234       {'Status': {'participate': 3, 'create': '3', 'activ': '1'}, 'comcount': 0, 'partrate': 100, 'rescount': 42}
英文:

You can use ast.literal_eval after removing the external " if any (your string would otherwise be an invalid input):

from ast import literal_eval

df['computed_data'] = df['computed_data'].str.strip('"').apply(literal_eval)

Output:

     ID                                                                                                     computed_data
0   987       {'Status': {'participate': 14, 'create': '10', 'activ': '0'}, 'rescount': 22, 'comcount': 0, 'partrate': 0}
1  4568  {'Status': {'participate': 49, 'create': '40', 'activ': '27'}, 'rescount': 22, 'comcount': 0, 'partrate': 73.47}
2  1234       {'Status': {'participate': 3, 'create': '3', 'activ': '1'}, 'comcount': 0, 'partrate': 100, 'rescount': 42}

huangapple
  • 本文由 发表于 2023年1月9日 18:26:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定