Python2.7:如何根据这样的特殊字符串将一列拆分为多列? [英] Python2.7: How to split a column into multiple column based on special strings like this?

查看:48
本文介绍了Python2.7:如何根据这样的特殊字符串将一列拆分为多列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程和 Python 的新手,所以非常感谢您的建议!

I'm a newbie for programming and python, so I would appreciate your advice!

我有一个这样的数据框.在信息"栏中,有 7 个不同的类别:活动、地点、团体、技能、景点、类型和其他.并且每个类别在 [ ] 中都有唯一的值.(即活动":[游览"])我想根据每个类别将信息"列分成 7 个不同的列,如下所示.

I have a dataframe like this. In 'info' column, there are 7 different categories: activities, locations, groups, skills, sights, types and other. and each categories have unique values within [ ].(ie,"activities":["Tour"]) I would like to split 'info' column into 7 different columns based on each category as shown below.

我想分配适当的列名,并在 [ ] 内为每行放置相应的唯一字符串.

I would like to allocate appropriate column names and also put corresponding unique strings within [ ] to each row.

有没有什么简单的方法可以像这样拆分数据帧?我正在考虑使用 str.split 函数将其分成几部分并稍后合并.但不确定这是最好的方法,我想看看是否有更复杂的方法来制作这样的数据框.

Is there any easy way to split dataframe like that? I was thinking to use str.split functions to split into pieces and merge everthing later. But not sure that is the best way to go and I wanted to see if there is more sophisticated way to make a dataframe like this.

感谢任何建议!

--更新--

print(dframe['info'])时,显示如下.

When print(dframe['info']), it shows like this.

推荐答案

好的,方法如下:

import pandas as pd
import ast

#Initial Dataframe is df
mylist = list(df['info'])
mynewlist = []

for l in mylist:
    mynewlist.append(ast.literal_eval(l))

df_info = pd.DataFrame(mynewlist)

#Add columns of decoded info to the initial dataset
df_new = pd.concat([df,df_info],axis=1)

#Remove the column info
del df_new['info']

这篇关于Python2.7:如何根据这样的特殊字符串将一列拆分为多列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆