如何在python中将嵌套列表处理为csv

2024-05-16 03:04:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在获取一些数据,当我在列表中获取这些数据时,我想将其写入csv文件(可能使用pandas)

我要转换的数据是列表形式的:

['Val Guene',
 'Vice President at Global Impact Partners',
 [['Vice President',
   'Global Impact Partners',
   'Apr 2019',
   'Present',
   '2 yrs 3 mos',
   'N/A',
   ' '],
  ['Executive Board Member',
   'Prismflare',
   'Nov 2018',
   'Present',
   '2 yrs 8 mos',
   'N/A',
   ''],
  ['Co-Founder',
   'Prismflare',
   'Jul 2017',
   'Nov 2018',
   '1 yr 5 mos',
   'N/A',
   ''],
  ['Executive Board Member',
   'SDS Masala',
   'Feb 2019',
   'Apr 2021',
   '2 yrs 3 mos',
   'New Delhi Area, India',
   ' '],
  ['Manager',
   'PwC',
   'Jul 2018',
   'Jan 2019',
   '7 mos',
   'Greater New York City Area',
   ''],
  ['Senior Associate', 'PwC', 'Jul 2015', 'Jun 2018', '3 yrs', 'N/A', ''],
  ['Experienced Associate', 'PwC', 'Jul 2013', 'Jun 2015', '2 yrs', 'N/A', ''],
  ['Associate', 'PwC', 'Aug 2012', 'Jun 2013', '11 mos', 'N/A', ''],
  ['Fellow',
   'Martindale Center for the Study of Private Enterprise',
   'Jan 2011',
   'Aug 2012',
   '1 yr 8 mos',
   'N/A',
   ' ']],
 [['Harvard University', 'Graduate', 'Philosophy', '2012', '2012'],
  ['Lehigh University',
   "Bachelor's degree",
   'Economics, International Relations, Psychology',
   '2008',
   '2012'],
  ['UWC-USA', 'International Baccalaureate', 'Economics', '2006', '2008']]]

我想知道我是否可以通过以下表格获得:

Name          Tag           Role            Company         Start        End and so on...

教育和经验的细节在不同的列表中有所不同,我尝试使用pandas和columns属性,但失败了。我正在努力使每一行都有一个经验/教育细节


Tags: 数据pandas列表viceglobalaprjunassociate
2条回答

您可以使用以下方法:

  1. 创建一个包含体验信息的数据框架
  2. 创建包含教育信息的数据框架
  3. 连接两个数据帧
  4. 创建您的CSV
# We suppose the indexes will be the sames in order to get always the correct data.

experience_data = data[2]
education_data = data[3]
name = data[0]
tag = data[1]

df_experience = pd.DataFrame(experience_data, columns=['Rol', 'Company', 'Start', 'End', 'Duration', 'City', 'Achieves (?)'])
df_experience['Name'] = name
df_experience['Tag'] = tag
df_experience = df_experience[['Name', 'Tag', 'Rol', 'Company', 'Start', 'End', 'Duration', 'City', 'Achieves (?)']]

df_education = pd.DataFrame(education_data, columns=['University', 'Degree', 'Field', 'Start Education', 'End Education'])
df = pd.concat([df_experience, df_education], axis=1)
df.to_csv('your/path/file.csv', index=False)

输出:click here

我假设您在某个数据库上进行迭代,在每次迭代中都会得到上面提到的嵌套列表

这里,对于一个人来说,你总共有9份工作和3份大学工作,所以,对于一个单身的有经验的人和一个单身的大学来说,这是没有意义的 您可以使用其中一个来创建数据帧

因此,让我们使用“体验”

让我们的这个嵌套列表由变量list1表示

list1[0]:-人名'

list1[1]:-'tag/current job'

list1[2]:-体验'

list1[3]:-大学'

在哪里,

t=pd.DataFrame(list1[2])
t['name'] = list1[0]
t['role'] = list1[1]
t

将为您提供所需的数据帧:

screenshot of output

我想这就是你要的

相关问题 更多 >