Python Forum
Transposing a dataframe without creating NaN values - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Transposing a dataframe without creating NaN values (/thread-39629.html)



Transposing a dataframe without creating NaN values - doug2019 - Mar-17-2023

Hi! I have the data like this in a .csv file:
index data
1 10
2 20
3 30
4 40
5 50
6 10
2 20
3 30
4 40
5 50
6. 60

And I would need them to be read like this in Python:
1 2 3 4 5 6
10 20 30 40 50 60
10 20 30 40 50 60

But it transposes the values and NaN appears between them as if it were 0 in a matrix:
1 2 3 4 5 6
10 NaN NaN NaN NaN. NaN
NaN 20 NaN NaN NaN NaN
NaN NaN 30 NaN NaN NaN
NaN NaN NaN 40 NaN NaN
NaN NaN NaN NaN 50 NaN
NaN NaN NaN NaN NaN 60


RE: Transposing a dataframe without creating NaN values - perfringo - Mar-18-2023

It important to be precise. If your data is in a file as provided then you could not get desired output. File has 11 rows.

Other than that - please provide your code.


RE: Transposing a dataframe without creating NaN values - jefsummers - Mar-18-2023

Indeed, not sure what the issue is. Please post your code. I did it as:
import pandas as pd

from_csv_data = [[1,10],[2,20],[3,30],[4,40],[5,50],[6,10],[2,20],[3,30],[4,40],[5,50],[6,60]]
df = pd.DataFrame(from_csv_data)
df0 = df.set_index(0)
df0
Output:
1 0 1 10 2 20 3 30 4 40 5 50 6 10 2 20 3 30 4 40 5 50 6 60
df1=df0.transpose()
df1
Output:
1 2 3 4 5 6 2 3 4 5 6 1 10 20 30 40 50 10 20 30 40 50 60