Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.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 在使用其他列作为分组变量时,在数据帧中转置列的子集?_Python_Performance_Pandas_Optimization_Dataframe - Fatal编程技术网

Python 在使用其他列作为分组变量时,在数据帧中转置列的子集?

Python 在使用其他列作为分组变量时,在数据帧中转置列的子集?,python,performance,pandas,optimization,dataframe,Python,Performance,Pandas,Optimization,Dataframe,假设我有一个熊猫数据帧(已经是数据帧格式): 我想将val1、val2和val2放在一列中,并将id1和id2作为分组变量。我可以使用这个非常复杂的代码: dfT = df.iloc[:,2::].T.reset_index(drop=True) n_points = dfT.shape[0] final = pd.DataFrame() for i in range(0, df.shape[0]): data = np.asarray([[df.ix[i,'id1']]*n_point

假设我有一个熊猫数据帧(已经是数据帧格式):

我想将
val1
val2
val2
放在一列中,并将
id1
id2
作为分组变量。我可以使用这个非常复杂的代码:

dfT = df.iloc[:,2::].T.reset_index(drop=True)
n_points = dfT.shape[0]
final = pd.DataFrame()
for i in range(0, df.shape[0]):
    data = np.asarray([[df.ix[i,'id1']]*n_points, 
                      [df.ix[i,'id2']]*n_points,
                      dfT.ix[:,i].values]).T
    temp = pd.DataFrame(data, columns=['id1','id2','val'])
    final = pd.concat([final, temp], axis=0)
要将我的数据帧转换为正确的格式,请执行以下操作:

    id1 id2 val
0   1.0 2.0 8.0
1   1.0 2.0 7.0
2   1.0 2.0 9.0
0   1.0 3.0 5.6
1   1.0 3.0 4.5
2   1.0 3.0 4.0
0   2.0 3.0 4.5
1   2.0 3.0 5.0
2   2.0 3.0 5.0
但必须有一种更有效的方法来实现这一点,因为在大型数据帧上,这需要花费很长时间

建议?

您可以与列
变量一起使用:

print (pd.melt(df, id_vars=['id1','id2'], value_name='val')
         .drop('variable', axis=1))

   id1  id2  val
0    1    2  8.0
1    1    3  5.6
2    2    3  4.5
3    1    2  7.0
4    1    3  4.5
5    2    3  5.0
6    1    2  9.0
7    1    3  4.0
8    2    3  5.0
另一个解决方案包括和:


甚至还有一个更简单的方法,可以使用(但尚未记录):


哇,一条线对七条线,真漂亮!是的,我也喜欢这个功能,但仍然没有在官方文档中记录:(我知道。我在ayhan的一个答案中了解到了这个功能。哦。也许我错过了这些答案,因为我在那段时间里没有活动。最近才开始。但我肯定ayhan使用过它。也许标签上没有这么说。我也很惊讶,也许搜索引擎遗漏了一些答案。对于那些使用
ipython
pd.lreshape???
或者
help(pd.lreshape)
将显示漂亮的文档字符串,包括一个小示例;)
print (pd.melt(df, id_vars=['id1','id2'], value_name='val')
         .drop('variable', axis=1))

   id1  id2  val
0    1    2  8.0
1    1    3  5.6
2    2    3  4.5
3    1    2  7.0
4    1    3  4.5
5    2    3  5.0
6    1    2  9.0
7    1    3  4.0
8    2    3  5.0
print (df.set_index(['id1','id2'])
         .stack()
         .reset_index(level=2, drop=True)
         .reset_index(name='val'))

   id1  id2  val
0    1    2  8.0
1    1    2  7.0
2    1    2  9.0
3    1    3  5.6
4    1    3  4.5
5    1    3  4.0
6    2    3  4.5
7    2    3  5.0
8    2    3  5.0
pd.lreshape(df, {'val': ['val1', 'val2', 'val3']}).sort_values(['id1', 'id2'])