[英]How to create column inside a column in a pandas dataframe?
Following is the code used to create a 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)
Below is the output of the DataFrame df
下面是 DataFrame df
的 output
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: " "}}
How can I convert the above DataFrame into any of the tabular format as shown below?如何将上述 DataFrame 转换为如下所示的任何表格格式?
You can create each column using eval
to convert the string
into a dictionary
and then accessing the required value, for example for the col 0
:您可以使用eval
创建每一列,将string
转换为dictionary
,然后访问所需的值,例如col 0
:
df[0] = df['Col 3'].apply(lambda x: eval(x)['tag1'][0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.