如何使用条件将循环中形成的新列分配给多个数据帧?

2024-10-06 12:05:35 发布

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

我有17个数据帧的列表:

CGdfs=[CGdf_2002,CGdf_2003,…,CGdf_2018]

我需要在每个数据帧中添加一个名为“custom_region”的新列。是否可以使用循环执行此操作

我尝试使用for循环将列分配给一个数据帧-CGdf_2002,如下所示:

custom_region = []

#for df in CGdfs:
for region, country in zip(CGdf_2002['region_of_headquarters'], CGdf_2002['country_of_headquarters']):
  if(region == 'Americas' and country == 'United States of America'):
    custom_region.append('US')
  elif(region == 'Americas' and country != 'United States of America'):
    custom_region.append('Americas(ex-US)') 
  elif(region == 'Africa'):
    custom_region.append('Africa') 
  elif(region == 'Oceania'):
    custom_region.append('Oceania')
  elif(region == 'Europe' and country == 'United Kingdom'):
    custom_region.append('UK')
  elif(region == 'Europe' and country != 'United Kingdom'):
    custom_region.append('Europe(ex-UK)')
  elif(region == 'Asia' and country == 'Japan'):
    custom_region.append('Japan')
  elif(region == 'Asia' and country != 'Japan'):
    custom_region.append('Asia(ex-Japan)')
  else:
    custom_region.append('')

CGdf_2002['custom_region'] = custom_region

我想对上面列表中的所有数据帧一起执行上述操作。请提出解决办法


Tags: andof数据forcustomcountryregionex