Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append item to list of different column in Pandas

I have a dataframe that looks like this:

dic = {'A':['PINCO','PALLO','CAPPO','ALLOP'],
       'B':['KILO','KULO','FIGA','GAGO'],
       'C':[['CAL','GOL','TOA','PIA','STO'],
            ['LOL','DAL','ERS','BUS','TIS'],
            ['PIS','IPS','ZSP','YAS','TUS'],
            []]}
df1 = pd.DataFrame(dic)

My goal is to insert for each row the element of A as first item of the list contained in column C. At the same time I want to set the element of B as last item of the list contained in C.

I was able to achieve my goal by using the following lines of code:

for index, row in df1.iterrows():
    try:
        row['C'].insert(0,row['A'])
        row['C'].append(row['B'])
    except:
        pass

Is there a more elegant and efficient way to achieve my goal maybe using some Pandas function? I would like to avoid for loops possibly.

like image 421
Federico Gentile Avatar asked Jan 20 '17 12:01

Federico Gentile


Video Answer


1 Answers

Inspired by Ted's solution but without modifying columns A and B:

def tolist(value):
    return [value]

df1.C = df1.A.map(tolist) + df1.C + df1.B.map(tolist)

Using apply, you would not write an explicit loop:

def modify(row):
    row['C'][:] = [row['A']] + row['C'] + [row['B']]

df1.apply(modify, axis=1)
like image 96
Mike Müller Avatar answered Sep 29 '22 05:09

Mike Müller