简体   繁体   English

有没有办法在熊猫中将单行转换为列

[英]is there a way to convert a single row to a column in pandas

Hi all I have been trying to convert this DataFrame大家好,我一直在尝试转换这个 DataFrame

col_1  col_2  col_3
item1  item2  item3
 $1xx   $2xx   $3xx

to this output:到这个输出:

col_1   NaN   col_2   NaN  col_3  NaN
item1  $1xx  item2   $2xx  item3  $3xx

I think you can avoid duplicated and also NaN s columns, so here is alternative with DataFrame.unstack , flatten MultiIndex Series anf create one row DataFrame by Series.to_frame with trnspose by DataFrame.T :我认为你可以避免重复和NaN的列,所以这里是DataFrame.unstack替代方案,展平MultiIndex Series创建一行 DataFrame by Series.to_frame和 trnspose by DataFrame.T

s = df.unstack()
s.index = s.index.map(lambda x: f'{x[0]}_{x[1]}')
df = s.to_frame().T
print (df)
  col_1_0 col_1_1 col_2_0 col_2_1 col_3_0 col_3_1
0   item1    $1xx   item2    $2xx   item3    $3xx

Another solution with DataFrame.melt : DataFrame.melt另一个解决方案:

df = df.reset_index().melt('index', value_name=0)
df.index = df['variable'] + '_' + df['index'].astype(str)

df = df[[0]].T
print (df)
  col_1_0 col_1_1 col_2_0 col_2_1 col_3_0 col_3_1
0   item1    $1xx   item2    $2xx   item3    $3xx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM