FlyingAura
FlyingAura

Reputation: 1601

Change dataframe from stacked to unstacked in Pandas

On the IRIS Dataset, when I convert a series to a dataframe (X_test.iloc[datapoint]].to_frame()), this is how its printed out (stacked):

sepal length (cm)    5.5
sepal width (cm)     2.6
petal length (cm)    4.4
petal width (cm)     1.2

When I convert a list of series points to a dataframe (df = df.append(result, ignore_index=True)), this is how its shown (unstacked):

   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.5               2.6                5.6               1.8

How do I convert the stacked layout to unstacked layout?

Upvotes: 0

Views: 75

Answers (1)

jezrael
jezrael

Reputation: 863226

You need transpose or use double list for return one row DataFrame:

print (X_test)
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.5               2.6                5.6               1.8
1                4.0               8.0                6.0               8.0

datapoint = 0
df = X_test.iloc[datapoint].to_frame().T
print (df)
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.5               2.6                5.6               1.8

df = X_test.iloc[[datapoint]]
print (df)
   sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)
0                5.5               2.6                5.6               1.8

Upvotes: 2

Related Questions