3

I have spent quiet some time on what seems to be very easy thing. All I want is to convert a numpy array to a Series and then combine Series to make a dataframe. I have two numpy arrays.

import numpy as np

rooms = 2*np.random.rand(100, 1) + 3
price = 265 + 6*rooms + abs(np.random.randn(100, 1))

I wanted to convert rooms and price to series and then combine the two series into a dataframe to make lmplot

So could any one tell me how to do that? Thanks.

2 Answers 2

4

you can use ravel() to convert the arrays to 1-d data:

pd.DataFrame({
     'rooms': rooms.ravel(),
    'price': price.ravel()
})
Sign up to request clarification or add additional context in comments.

2 Comments

Okay thanks, but would it be possible to convert it to a series because it looks so obvious to do that. Why is it not possible or not first preference? Actually a bit curious to find out how to convert a one dimensional array to a Serious.
You can also do pd.Series(rooms.ravel()) and then get the dataframe. I thought since you want a dataframe in the end, you might go through a dictionary.
2

The problem with passing the arrays directly to pd.Series is the dimensionality: rooms and price are 2d-array of shape (100,1) while pd.Series requires a 1d-array. To reshape them you can use different methods, one of which is .squeeze(), namely:

import pandas as pd
import numpy as np

rooms = 2*np.random.rand(100, 1) + 3
price = 265 + 6*rooms + abs(np.random.randn(100, 1))

rooms_series = pd.Series(rooms.squeeze())
price_series = pd.Series(price.squeeze())

Now to go from series to dataframe you can do:

pd.DataFrame({'rooms': rooms_series,
              'price': price_series})

Or directly from the numpy arrays:

pd.DataFrame({'rooms': rooms.squeeze(),
              'price': price.squeeze()})

1 Comment

Thanks to you too. Yes that was the error I was getting although shape shows (rows x col) and probably means 100 rows and 1 column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.