Home > database >  How to extend a list inside a pandas dataframe
How to extend a list inside a pandas dataframe

Time:01-04

I have a pandas data frame, and each element of one of its columns is a list. Then I have a list with the same amount of elements as rows in the pandas data frame; I want to extend the list inside pandas with this new list.

So, for example, if this is the data frame.

my_column
[1, 2]
[3, 4]

and this is the external list

[[5, 6], [7, 8, 9]]

I want to extend each of the lists of the data frame, so the final result is:

my_column
[1, 2, 5, 6]
[3, 4, 7, 8, 9]

For now, what I have is:

for index, row in data.iterrows():
    df["my_column"].loc[index] = row["my_column"].extend(external_list[index])

Is there a more pythonic way?

CodePudding user response:

df = pd.DataFrame({'my_column':[[1, 2], [3, 4]]})
lst = [[5, 6], [7, 8, 9]]

One way:

df['my_column']  = pd.Series(lst) 

Another way: You can zip the column values with list values and use list comprehension:

df['my_column'] = [l1   l2 for l1, l2 in zip(df['my_column'].tolist(), lst)]

Output:

         my_column
0     [1, 2, 5, 6]
1  [3, 4, 7, 8, 9]

CodePudding user response:

I am not sure whether or not it's pythonic enough but you can do it this way:

data = {"my_column":[[1, 2], [3, 4]]}
df = pd.DataFrame(data)

list2 = [[5, 6], [7, 8, 9]]

df["my_column"] = [list1   list2[i] for i, list1 in df["my_column"].iteritems()]
  •  Tags:  
  • Related