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.
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)
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With