简体   繁体   中英

How to add a new column to multiple pandas dataframes based on a condition?

I have 17 data frames to which I wish to add a new column using for loop based on certain conditions. Any suggestions on how this can be done?

I have a list called custom_region = [] and 17 dataframes again stored in a list called CGdfs .

CGdfs = [CGdf_2002, CGdf_2003, CGdf_2004, CGdf_2005, CGdf_2006, CGdf_2007, CGdf_2008, CGdf_2009, CGdf_2010, CGdf_2011, CGdf_2012, CGdf_2013, CGdf_2014, CGdf_2015, CGdf_2016, CGdf_2017, CGdf_2018]

I am appending new values to custom_region based on certain conditions in a loop. This list I have to finally append to each of these dataframes to create a column for each of them.

So, custom_region[0] to CGdf_2002
custom_region[1] to CGdf_2003 and so on..

I didn't understand your question really well , but I suppose that your custom_region is already filled with columns you want to append to CGdf dataframes.

If so you have to loop through CGdf and for each dataframe you will concat a column from custom_region

how about this :

i = 0
j = 0 

for i in range(len(CGdfs)) : 
  CGdfs[i] = pd.concat([CGdfs[i],custom_region[j]],axis=1)
  j = j + 1 



The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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