系列:动态转置优化

Series : dynamic transposition optimization

我想将 Pandas 系列转换为转置数据帧,其中 key/values 的数量是动态的。然后,转置数据框也必须具有动态列数。

我使用 to_frame() 和 to_transpose() 方法成功了,但我想优化我的代码。 更准确地说,我需要使用 reset_index() 方法,然后删除 "index" 创建的无用的列......我认为它可以更好地实现。

请查找我当前的代码:

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))

请找到预期结果的说明:picture of expected result

你有什么解决方案可以使用 "standards" Pandas series/dataframes methods/options 来优化我的代码吗?

感谢您的帮助:)

使用DataFrame.transpose + DataFrame.set_index:

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

示例:

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