lundi 1 août 2016

Adding Columns if they exist in the Dataframe: pandas

I have a Dataframe, where I want to add three columns and make it one, and I want it for the columns which exits in the data frame. so for example, I want to add following columns

List_ID=['ID1','ID2','ID3'] 
df # Df is the data frame

I am trying following for summing up the "if exists" columns, but not able to.

ID=sum[[col for col in list_ID if col in df.columns]] 

And explaining ID1, ID2 columns they can be like

df = pd.DataFrame({'Column 1':['A', '', 'C', ' '],'Column 2':[' ', 'F', ' ', '']})  
and my new column ID will look like 

In[34]: a=df['Column 1'] + (df['Column 2'])

In[35]: a

   Out[35]: 
    0    A 
    1    F
    2    C 
    3       

All suggestions are welcome

Aucun commentaire:

Enregistrer un commentaire