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 |
CodePudding user response:
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
CodePudding user response:
Suggest trying
df.transpose()
for the purpose.
CodePudding user response:
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
CodePudding user response:
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)