转换Python字典以创建单独的列

问题描述 投票:0回答:1

I want to organize the data into two separate columns, 'cl1=census block' and 'cl2=visit' columns where the dict-key is the census block column and dict-value is the visit column. I have tried but cannot seem to get ahead. Can someone help with the solution

我想将数据组织成两个单独的列,

cl1=census block
cl2=visit columns
,其中dict-key是人口普查块列,dict-value是访问列。我已经尝试过,但似乎无法取得进展。

有人可以帮忙解决吗?

df['cbg_group'] = df['visitor_home_cbgs'].str.strip('{}')

# Split the 'visitor_home_cbgs' column into separate 'census block' and 'visit' columns
df[['census_block', 'visit']] = df['visitor_home_cbgs'].str.split(':', expand=True)
df
python pandas data-processing
1个回答
0
投票

我认为这可能有用:

df['census_block', 'visit'] = lambda k, v: [i for i in df[vistor_home_cbgs]].items()

您介意给我一个数据集的样本,这样我就不必尝试重新创建它或找到它或类似的东西吗?并且'{}'不是字符串文字,它只是数据结构是字典类型的指示符。我认为您只需要迭代数据框即可为每一行生成字典,然后迭代每个字典并将键和值分成两个单独的列以及您想要的任何数据结构。

© www.soinside.com 2019 - 2024. All rights reserved.