我有以下
pandas
数据框:
import pandas as pd
df2 = pd.DataFrame({
'nombreNumeroUnico': ['UP2_G1_B', 'UP2_G2_B'],
'pMax': [110.0, 110.0]
})
df2
((Out [1])):
nombreNumeroUnico pMax
0 UP2_G1_B 110.0
1 UP2_G2_B 110.0
我想把它改成:
UP2_G1_B UP2_G2_B
0 110 110
到目前为止,我能够使用数据透视函数对其进行转换,但我没有得到我想要的确切结果。
df2.pivot(index=None, columns="nombreNumeroUnico", values="pMax")
((Out [57])):
nombreNumeroUnico UP2_G1_B UP2_G2_B
0 110.0 NaN
1 NaN 110.0
但这不是我想要的确切结果。怎样才能得到预期的结果?
请使用
df2.set_index('nombreNumeroUnico').T.reset_index(drop=True)
测试代码:
import pandas as pd
df2 = pd.DataFrame({
'nombreNumeroUnico': ['UP2_G1_B', 'UP2_G2_B'],
'pMax': [110.0, 110.0]
})
result_df = df2.set_index('nombreNumeroUnico').T.reset_index(drop=True)
result_df.columns.name = None
print(result_df)
输出:
UP2_G1_B UP2_G2_B
0 110.0 110.0
一种可能的解决方案是:
df = df2.pivot_table(columns="nombreNumeroUnico", values="pMax")
df.columns.name = None
df = df.reset_index(drop=True)
然后:
df
((Out [84])):
UP2_G1_B UP2_G2_B
0 110.0 110.0