1

我是编程语言的初学者,因此非常感谢您的帮助和支持。

这是 DataFrame,一列的数据是 JSON 类型?数据的。

ID, Name, Information
1234, xxxx, '{'age': 25, 'gender': 'male'}'
2234, yyyy, '{'age': 34, 'gender': 'female'}'
3234, zzzz, '{'age': 55, 'gender': 'male'}'

我想将这个 DataFrame 隐藏如下。

ID, Name, age, gender
1234, xxxx, 25, male
2234, yyyy, 34, female
3234, zzzz, 55, male

我发现 ast.literal_eval() 可以将 str 转换为 dict 类型,但我不知道如何编写这个问题的代码。

您能否举一些可以解决此问题的代码示例?

4

2 回答 2

0

给定test.csv

ID,Name,Information
1234,xxxx,"{'age': 25, 'gender': 'male'}"
2234,yyyy,"{'age': 34, 'gender': 'female'}"
3234,zzzz,"{'age': 55, 'gender': 'male'}"
  • 用 with 读取文件pd.read_csv并使用converters参数 with ast.literal_eval,这会将Information列中的数据从str类型转换为dict类型。
  • 用于pd.json_normalize将 with 键解包dict为行中的列标题和值
  • .join规范化的列df
  • .dropInformation列_
import pandas as pd
from ast import literal_eval

df = pd.read_csv('test.csv', converters={'Information': literal_eval})

df = df.join(pd.json_normalize(df.Information))

df.drop(columns=['Information'], inplace=True)

# display(df)
     ID  Name  age  gender
0  1234  xxxx   25    male
1  2234  yyyy   34  female
2  3234  zzzz   55    male

如果数据不是来自 csv 文件

import pandas as pd
from ast import literal_eval

data = {'ID': [1234, 2234, 3234],
        'Name': ['xxxx', 'yyyy', 'zzzz'],
        'Information': ["{'age': 25, 'gender': 'male'}", "{'age': 34, 'gender': 'female'}", "{'age': 55, 'gender': 'male'}"]}

df = pd.DataFrame(data)

# apply literal_eval to Information
df.Information = df.Information.apply(literal_eval)

# normalize the Information column and join to df
df = df.join(pd.json_normalize(df.Information))

# drop the Information column
df.drop(columns=['Information'], inplace=True)
于 2020-08-13T00:56:48.213 回答
0
  1. 如果第三列是 JSON 字符串,'则无效,它应该是",所以我们需要解决这个问题。
  2. 如果第三列是 python 的字符串表示dict,您可以使用eval它来转换它。

拆分第三列类型dict并合并到原始的代码示例DataFrame

data = [
  [1234, 'xxxx', "{'age': 25, 'gender': 'male'}"],
  [2234, 'yyyy', "{'age': 34, 'gender': 'female'}"],
  [3234, 'zzzz', "{'age': 55, 'gender': 'male'}"],
]

df = pd.DataFrame().from_dict(data)

df[2] = df[2].apply(lambda x: json.loads(x.replace("'", '"'))) # fix the data and convert to dict
merged = pd.concat([df[[0, 1]], df[2].apply(pd.Series)], axis=1)
于 2020-08-13T00:37:32.787 回答