How can append each column with one fixed one dimensional array in a dataframe?
df = pd.DataFrame([
['234', '434', '471', '4744', '477'],
['2.4', '2.4', '2.4'],
])
df.columns = ['col 1', 'col 2', 'col 3', 'col 4', 'col 5']
df
col 1 col 2 col 3 col 4 col 5
234 434 473 4744 477
2.4 2.4 2.4 2.4 2.4
oneD_array = [1, 0, 0, 1, 2, 3]
how can I add my oneD_array
to the each column of given dataframe df
.
expected output
df
col 1 col 2 col 3 col 4 col 5
234 434 473 4744 477
2.4 2.4 2.4 2.4 2.4
1 1 1 1 1
0 0 0 0 0
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
CodePudding user response:
Let's repeat the lst
n times then concat
it to the dataframe
# It's ok to create a n times repeated list like this to create dataframe, but not suitable if you want to use it as variable
out = pd.concat([df, pd.DataFrame([oneD_array] * len(df.columns), index=df.columns).T],
ignore_index=True)
print(out)
col 1 col 2 col 3 col 4 col 5
0 234 434 471 4744 477
1 2.4 2.4 2.4 None None
2 1 1 1 1 1
3 0 0 0 0 0
4 0 0 0 0 0
5 1 1 1 1 1
6 2 2 2 2 2
7 3 3 3 3 3
CodePudding user response:
You can use np.repeat
to prepare the additional rows:
n_col = df.shape[1]
arr = np.array(oneD_array).repeat(n_col).reshape(-1, n_col)
result = pd.concat([df, pd.DataFrame(arr, columns=df.columns)], ignore_index=True)