简体   繁体   English

将分隔项的python列表转换为pandas数据框

[英]Converting python list of delimited items in to a pandas data frame

I have a list like this where items are separated by ":".我有一个这样的列表,其中项目用“:”分隔。

   x=['john:42:engineer',
      'michael:29:doctor']

Is there an way to change this in to a data frame like below by defining columns Name, Age and Occupation?有没有办法通过定义名称、年龄和职业列来将其更改为如下所示的数据框?

    Name    Age Occupation
0   john    42  engineer
1   michael 29  doctor

You can just use split :你可以只使用split

pd.DataFrame([y.split(':') for y in x], columns = ['Name','Age', 'Occupation'])

Output:输出:

      Name Age Occupation
0     john  42   engineer
1  michael  29     doctor

I will do我会做

df = pd.Series(x).str.split(':',expand=True)
df.columns = ['Name','Age', 'Occupation']
df
Out[172]: 
      Name Age Occupation
0     john  42   engineer
1  michael  29     doctor

Not sure this is the best approach, but...不确定这是最好的方法,但是......

x = ['john:42:engineer', 'michael:29:doctor']
x = [i.split(':') for i in x]
pd.DataFrame({'name': [i[0] for i in x], 'age': [i[2] for i in x], 'occupation': [i[1] for i in x]})

Output:

    name    age occupation
0   john    42  engineer
1   michael 29  doctor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM