如何在熊猫数据框中的列内创建列?

时间:2021-03-17 10:59:14

标签: python pandas dataframe

以下是用于创建 DataFrame 的代码。

import pandas as pd
cols = ['Col 1', 'Col 2', 'Col 3']
data = [['Row 1', '1.0', '{"tag1" : {0: \" \", 1: \" \"}, "tag2": {2: \" \", 3: \" \"}}'], ['Row 2', '2.0', '{"tag1" : {0: \" \", 1: \" \"}, "tag2": {2: \" \", 3: \" \"}}']]
df = pd.DataFrame(columns = cols, data = data)

以下是 DataFrame df

的输出
   Col 1 Col 2                                                  Col 3
0  Row 1   1.0  {"tag1" : {0: " ", 1: " "}, "tag2": {2: " ", 3: " "}}
1  Row 2   2.0  {"tag1" : {0: " ", 1: " "}, "tag2": {2: " ", 3: " "}}

如何将上述 DataFrame 转换为如下所示的任何表格格式?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用 eval 创建每一列,将 string 转换为 dictionary,然后访问所需的值,例如 col 0

df[0] = df['Col 3'].apply(lambda x: eval(x)['tag1'][0])