I would like to add new columns to a data frame using function and values from the original data frame
Create the dataframe
df = pd.DataFrame({'f1' : np.random.randn(10),
'f2' : np.random.randn(10),
'f3' : np.random.randn(10),
'f4' : np.random.randn(10),
'f5' : np.random.randn(10)})
Test function to be applied to the existing columns
def testfun(x,n):
return x * n
Arguments for the function - each new column has different arguments
colnum = [1,2,3,4,5]
Create new columns names for the new columns to add to the data frame
newcol = [s + "_D" for s in df.columns]
Loop through the existing columns applying the function and appropriate argument for that column. Each new column will be assigned an unique name.
This part function does not work!
for s in range(len(df.columns)):
df = df.assign(newcol[s] = testfun(df[[df.columns[s]]], s))
The new data frame should contain 10 columns.