spb
spb

Reputation: 175

Pandas : Convert 1D dataframe to 2D dataframe

I have pandas dataframe whose shape is (4628,). How do I change the shape of dataframe to (4628,1)?

Upvotes: 0

Views: 3116

Answers (2)

Serene
Serene

Reputation: 21

You can use the function called reshape(). It's easy to use. Run the code and you'll see the result from (4628,) to (4628,1).

import pandas as pd

df = pd.DataFrame(range(1,4629))
print(df)
df = df.values.reshape(-1)
print(df.shape)
df = df.reshape(-1,1)
print(df.shape)

Results:

......

[4628 rows x 1 columns]

(4628,)

(4628, 1)

Upvotes: 2

Ynjxsjmh
Ynjxsjmh

Reputation: 30002

You might have a Series, you can turn it into DataFrame with Series.to_frame

s = pd.Series(range(10))

out = s.to_frame('col_name') # or .to_frame()
print(s.shape)

(10,)

print(out.shape)

(10, 1)

Don't know how you get that Series, if you use a label like df['a'], you can try passing a list of labels instead, like df[['a']]

Upvotes: 2

Related Questions