Adding columns to pandas dataframe dynamically

I have the following code to load a dataframe

import pandas as pd

ufo = pd.read_csv('csv_path')
print ufo.loc[[0,1,2] , :]

which gives the following result, see csv structure

          City Colors Reported Shape Reported State             Time
0       Ithaca             NaN       TRIANGLE    NY   6/1/1930 22:00
1  Willingboro             NaN          OTHER    NJ  6/30/1930 20:00
2      Holyoke             NaN           OVAL    CO  2/15/1931 14:00

Now I want to add an extra column based on an existing column. I have a list that consists of indices of the participating columns. This may be 0,1 , or 0,2,3 or 1,2,3 .

I need to create it dynamically. I could come up with the following

df1['combined'] = df1['City']+','+df1['State']

Index room does not work. I want to join these columns. using','.join()

+4
source share
3 answers

, , join, str, [] , apply, :

df[[0,2,3]].apply(','.join, axis=1)

#0      Ithaca,TRIANGLE,NY
#1    Willingboro,OTHER,NJ
#2         Holyoke,OVAL,CO
#dtype: object
+3

l, pd.Series.cat:

df[df.columns[l[0]]].astype(str).str.cat([df[df.columns[i]].astype(str) for i in l[1: ]], sep=',')

In [18]: df = pd.DataFrame({'a': [1, 2], 'b': [2, 'b'], 'c': [3, 'd']})

In [19]: df[df.columns[l[0]]].astype(str).str.cat([df[df.columns[i]].astype(str) for i in l[1: ]], sep=',')
Out[19]: 
0    1,2
1    2,b
Name: a, dtype: object
+3
def dyna_join(df, positions):
    return pd.concat([df, df.iloc[:, positions].apply(','.join, 1).rename('new_col')], axis=1)


dyna_join(df, [0, -2])

enter image description here

+3
source

Source: https://habr.com/ru/post/1660080/


All Articles