msa
msa

Reputation: 735

add list of lists to pandas dataframe, where each item of the list is a new column

I have 10 list of lists (variable length) looking like this, but each inside list is of the same length.

[[0.2908717393875122, 0.012684155255556107, -0.0040715765208005905], [0.02942436747252941, 0.011299843899905682, 0.009102505631744862], [0.0382646806538105, 0.004623611457645893, 0.004776048939675093]]

I also have a list of 10 dataframes, where each df looks like this:

Second | Number |
2      |   B    |
3      |   B    |
4      |   B    |

What I would like to do is add this list of list to each dataframe, where the resutls looks like this:

 Second    | Number | V1                | V2                  |V3
    2      |   B    |0.2908717393875122 |0.012684155255556107 | -0.0040715765208005905
    3      |   B    |0.02942436747252941| 0.011299843899905682| 0.009102505631744862
    4      |   B    |0.0382646806538105 | 0.004623611457645893| 0.004776048939675093

I know how to append a single list to the existing dataframe (and it works), but I would like to to do this all in one go.

df['V1'] = list

Upvotes: 0

Views: 998

Answers (2)

Anurag Dabas
Anurag Dabas

Reputation: 24322

lst=[[0.2908717393875122, 0.012684155255556107, -0.0040715765208005905], [0.02942436747252941, 0.011299843899905682, 0.009102505631744862], [0.0382646806538105, 0.004623611457645893, 0.004776048939675093]]

Just simply use:-

df[['V1','V2','V3']]=lst

Now if you print df you will get your desired output:-

 Second Number  V1              V2          V3
0   2      B    0.290872    0.012684    -0.004072
1   3      B    0.029424    0.011300    0.009103
2   4      B    0.038265    0.004624    0.004776

Edit by @msa:

first: new_cols = ['V1', 'V2', 'V3'] 
df = df.reindex(df.columns.union(new_cols), axis=1) 

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150825

Try:

for i in range(10):
    d = pd.DataFrame(list_of_list[i], 
                     columns=['V1','V2','V3'],
                     index=list_df[i].index)
    list_df[i] = list_df[i].join(d)

Upvotes: 0

Related Questions