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
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).
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