I got the variable 'v' which is a 2d array:
in = v
out =
array([[ 217.1, 252.5],
[ 73. , 53. ],
[ 83. , 827. ],
...,
[ 129. , 1214. ],
[ 118.6, 908.2],
[ 90. , 99.5]])
I have a dataframe with multiple columns and now I want to add this array to it in 2 seperate columns. So:
x y
271.1 252.5
and so on.
How can I do this?
I tried:
df["Q_pred"],df["r_pred"] = v
but this gives the error:
ValueError: too many values to unpack (expected 2)
I honestly don't know how to do it.
How to convert 1-D arrays as columns into a 2-D array in Python? Let’s see a program to convert 1-D arrays as columns into a 2-D array using NumPy library in Python. So, for solving this we are using numpy.column_stack () function of NumPy.
If you want to convert an array to a dataframe and create column names you’ll just do as follows: df = pd.DataFrame (numpy_array, columns= [ 'digits', 'words' ]) Code language: JavaScript (javascript) In the image below, you will see the resulting dataframe.
It's easy to add multiple columns at once to an existing DataFrame. Just assign using a list of your new columns, and convert your numpy array to a DataFrame: Q_pred r_pred 0 217.1 252.5 1 73.0 53.0 2 83.0 827.0 3 129.0 1214.0 4 118.6 908.2 5 90.0 99.5
Pandas is one of those packages and makes importing and analyzing data much easier. Let’s discuss all different ways of selecting multiple columns in a pandas DataFrame. Given a dictionary which contains Employee entity as keys and list of those entity as values. Select Second to fourth column. Example 2: Select one to another columns.
That's a correct idea, but you'll need the transformed matrix:
import pandas as pd
import numpy as np
v = np.array([[ 217.1, 252.5],
[ 73. , 53. ],
[ 83. , 827. ],
[ 129. , 1214. ],
[ 118.6, 908.2],
[ 90. , 99.5]])
df = pd.DataFrame()
df["Q_pred"], df["r_pred"] = v.T
Q_pred r_pred
0 217.1 252.5
1 73.0 53.0
2 83.0 827.0
3 129.0 1214.0
4 118.6 908.2
5 90.0 99.5
This works with an already populated dataframe, too:
df["asdf"],df["qwetz"] = v.T
Q_pred r_pred asdf qwetz
0 217.1 252.5 217.1 252.5
1 73.0 53.0 73.0 53.0
2 83.0 827.0 83.0 827.0
3 129.0 1214.0 129.0 1214.0
4 118.6 908.2 118.6 908.2
5 90.0 99.5 90.0 99.5
or shorter without transformation and in one line:
df = pd.DataFrame(v, columns=['Q_pred', 'r_pred'])
Q_pred r_pred
0 217.1 252.5
1 73.0 53.0
2 83.0 827.0
3 129.0 1214.0
4 118.6 908.2
5 90.0 99.5
Another way is to index the column like this:
df["Q_pred"],df["r_pred"] = v[:,0], v[:,1]
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