Python 有没有办法将一行转换为一列
嗨,我一直在尝试转换这个数据帧Python 有没有办法将一行转换为一列,python,pandas,Python,Pandas,嗨,我一直在尝试转换这个数据帧 col_1 col_2 col_3 item1 item2 item3 $1xx $2xx $3xx 对于此输出: col_1 NaN col_2 NaN col_3 NaN item1 $1xx item2 $2xx item3 $3xx 我认为您可以避免重复,也可以避免NaNs列,因此这里有另一种选择,展平多索引系列anf创建一行数据帧by by with trnspose by: 另一个解决方案包括: s =
col_1 col_2 col_3
item1 item2 item3
$1xx $2xx $3xx
对于此输出:
col_1 NaN col_2 NaN col_3 NaN
item1 $1xx item2 $2xx item3 $3xx
我认为您可以避免重复,也可以避免NaNs列,因此这里有另一种选择,展平多索引系列anf创建一行数据帧by by with trnspose by: 另一个解决方案包括:
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
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