I want to create a set of n columns in a DataFrame each assigned a separate value using a list comprehension.
#My original dataframe
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
A B
0 1 4
1 2 5
2 3 6
#Expected output -
pd.concat([df, pd.DataFrame(np.tile(np.array([5,10,15,20,25])[:,None], 3).T)], axis=1)
A B 0 1 2 3 4
0 1 4 5 10 15 20 25
1 2 5 5 10 15 20 25
2 3 6 5 10 15 20 25
I need to do it in this fashion -
#ROUGH structure of the code that I am looking for -
n = "number of columns i want to add"
df[[i for i in range(n)]] = numpyarray #whose shape is (n,3)
The error that I face is quite obvious -
KeyError: "None of [Int64Index([0, 1, 2], dtype='int64')] are in the [columns]"
#AND
SyntaxError: can't assign to list comprehension
I have read other solutions which allow adding multiple columns but this one specifically needs a loop with an iterator of n because -
- The data frame may need 25 columns added and that doesn't depend on the array of values
- The array of values can be (3, 15) which means that last 10 of the columns will not take their values from the array
- The prefered solution would be a list comprehension since the list of columns that I would be creating (25 for example) come from a list comprehension based iterator