Ad

Series : Dynamic Transposition Optimization

I would like to convert a Pandas Series to transposed Dataframe, where number of key/values is dynamic. Then, transposed Dataframe must have dynamic number of columns also.

I succeeded using to_frame() and to_transpose() methods, but I would like to optimize my code. More precisely, I need to use the reset_index() method and then drop the "index" created column which is useless... I supposed it can be better achieved.

Please find my current code:

current_case_details = row.to_frame().transpose().reset_index()
current_case_details.drop(columns=['index'], inplace=True)
print("CURRENT CASE DETAILS:\n{0}\n".format(current_case_details))

Please find an illustration of expected result : picture of expected result

Do you have any solution to optimize my code using "standards" Pandas series/dataframes methods/options ?

Thank you for your help :)

Ad

Answer

Use DataFrame.transpose + DataFrame.set_index:

new_df=serie.to_frame().T.reset_index(drop=True)

Example:

serie=pd.Series([1,2,3,'AA'],['c1','c2','c3','c4'],name='Value')
print(serie)

c1     1
c2     2
c3     3
c4    AA
Name: Value, dtype: object

new_df=serie.to_frame().T.reset_index(drop=True)
print(new_df)

  c1 c2 c3  c4
0  1  2  3  AA 
Ad
source: stackoverflow.com
Ad