Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何同时熔化2根柱子?_Python_Python 3.x_Pandas - Fatal编程技术网

Python 如何同时熔化2根柱子?

Python 如何同时熔化2根柱子?,python,python-3.x,pandas,Python,Python 3.x,Pandas,在Pandas中,我有以下数据框: id1 id2 t1 l1 t2 l2 0 1 2 a b c d 1 3 4 g h i j 我想同时熔化两根柱子。即,所需输出为: id1 id2 tz lz 0 1 2 a b 1 1 2 c d 2 3 4 g h 3 3 4 i j 我知道标准熔炼: d.melt(id_vars=['id1', 'id2'],

在Pandas中,我有以下数据框:

   id1 id2 t1  l1  t2  l2 
0  1   2   a   b   c   d
1  3   4   g   h   i   j
我想同时熔化两根柱子。即,所需输出为:

   id1 id2 tz  lz  
0  1   2   a   b
1  1   2   c   d
2  3   4   g   h
3  3   4   i   j
我知道标准熔炼:

d.melt(id_vars=['id1', 'id2'],
       value_vars=['t1', 't2', 'l1', 'l2'])
但这会叠加所有列

   id1  id2 variable value
0    1    2       t1     a
1    3    4       t1     g
2    1    2       t2     c
3    3    4       t2     i
4    1    2       l1     b
5    3    4       l1     h
6    1    2       l2     d
7    3    4       l2     j
我怎么能一次熔化两根柱子呢?比如:

d.melt(id_vars=['id1', 'id2'],
       value_vars={('t1', 'l1'): 'tz', ('t2', 'l2'): 'lz'})

太好了。

这是从宽到长的

pd.wide_to_long(df,['t','l'],i=['id1','id2'],j='drop').reset_index(level=[0,1])
Out[52]: 
      id1  id2  t  l
drop                
1       1    2  a  b
2       1    2  c  d
1       3    4  g  h
2       3    4  i  j

您可以在此处和之后使用
melt
两次,以获得所需的输出:

t = d.melt(id_vars=['id1', 'id2'], value_vars=['t1', 't2'], value_name='tz').drop('variable', axis=1)
l = d.melt(id_vars=['id1', 'id2'], value_vars=['l1', 'l2'], value_name='lz').iloc[:, -1:]

df = pd.concat([t, l], axis=1).sort_values('id1')

输出

print(df)
   id1  id2 tz lz
0    1    2  a  b
2    1    2  c  d
1    3    4  g  h
3    3    4  i  j
哪个部分使它选择(t1,l1)和(t2,l2),而不是(t1,t2)和(l1,l2)。它是否取决于列在数据帧中的显示顺序?如果是,我可以指定订单吗?谢谢。@hyperio,是stubnames