Reputation: 184
What's the best practice for such a simple task?
Is there any way to speed up the messy lines of code with a simple method?
Let's say we have the following raw data:
#Example Data
df = pd.read_csv('example.csv', header = None, sep=';')
display(df)
To manipulate the data appropriately we transpose and edit:
#Transpose the Dataframe
df = df.transpose()
display(df)
#Set the first row as a header
header_row = 0 #<-- Input, should be mandatory? could it be default?
#Set the column names to the first row values
df.columns = df.iloc[header_row]
#Get rid of the unnecessary row
df = df.drop(header_row).reset_index(drop=True)
#Display final result
display(df)
Upvotes: 1
Views: 264
Reputation: 1102
you can simply do that by
df.set_index(0,inplace=True)
df.T
an example of same kind is given below
df2=pd.DataFrame({"Col":[9,8,0],"Row":[6,4,22],"id":[26,55,27]})
df2
Col Row id
0 9 6 26
1 8 4 55
2 0 22 27
df2.set_index("id",inplace=True)
df2.T
id 26 55 27
Col 9 8 0
Row 6 4 22
Upvotes: 1