Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a column in a pandas df with a repeated sequence of values

Tags:

python

pandas

I want to add a column to a pandas DataFrame that has a sequence of int or even str.

This is the pandas DataFrame:

import pandas as pd

df = [{"us": "t1"},
{"us": "t2"},
{"us": "t3"},
{"us": "t4"},
{"us": "t5"},
{"us": "t6"},
{"us": "t7"},
{"us": "t8"},
{"us": "t9"},
{"us": "t10"},
{"us": "t11"},
{"us": "t12"}
    ]
df = pd.DataFrame(df)
df

I just want to add a column of a list of int or str like these:

list_int = [1, 2, 3, 4]

list_str = ['one','two','three','four']

Of course the code df['list_int']=list_int is not working because of the length.

The output should be this:

    us   list_int  list_str
0   t1      1        one
1   t2      2        two
2   t3      3        three
3   t4      4        four
4   t5      1        one
5   t6      2        two
6   t7      3        three
7   t8      4        four
8   t9      1        one
9   t10     2        two
10  t11     3        three
11  t12     4        four
like image 474
pesc9 Avatar asked Nov 24 '25 02:11

pesc9


1 Answers

You can use np.tile:

df['list_int'] = np.tile(list_int, len(df)//len(list_int) + 1)[:len(df)]

or simply

df['list_int'] = np.tile(list_int, len(df)//len(list_int)]

if len(df) is divisible by len(list_int).

like image 56
Quang Hoang Avatar answered Nov 25 '25 14:11

Quang Hoang