2

I have this sample code below that turns a Python list of lists into a pandas DataFrame, but I need to DataFrame orientation to be inversed, any idea how to achieve this?

import numpy as np
import pandas as pd
from IPython.display import display, HTML

i = np.zeros(10)
i.fill(40)

j = np.zeros(10)
j.fill(60)

df = pd.DataFrame([i, j])

display(df)

The output of this is a structure like this:

0 1 2 3 4 5 6 7 8 9
0 40 40 40 40 40 40 40 40 40 40
1 60 60 60 60 60 60 60 60 60 60

But, what I want is to get a structure like this, how can I turn a list of lists into such format?

0 1
40 60
40 60
40 60
40 60
40 60
40 60
40 60
40 60
40 60
1
  • 1
    How about : df.T Commented Aug 31, 2022 at 14:22

4 Answers 4

2

Let's try to create a two columns dataframe directly

df = pd.DataFrame(zip(i, j))
# or specify the column header
df = pd.DataFrame(zip(i, j), columns=['a', 'b'])
print(df)

      0     1
0  40.0  60.0
1  40.0  60.0
2  40.0  60.0
3  40.0  60.0
4  40.0  60.0
5  40.0  60.0
6  40.0  60.0
7  40.0  60.0
8  40.0  60.0
9  40.0  60.0
Sign up to request clarification or add additional context in comments.

Comments

2

just transpose the dataframe :

df = df.T

or prepare your df the way you want at the first place:

df = pd.DataFrame({0: i, 1: j})

output:

>>
      0     1
0  40.0  60.0
1  40.0  60.0
2  40.0  60.0
3  40.0  60.0
4  40.0  60.0
5  40.0  60.0
6  40.0  60.0
7  40.0  60.0
8  40.0  60.0
9  40.0  60.0

Comments

1

Suggest trying

df.transpose()

for the purpose.

Comments

0

If you want to correct this before creating your dataframe, you can use numpy.column_stack and then create the dataframe.

inp_arr = np.column_stack((i,j))
df = pd.DataFrame(inp_arr)

Comments

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.