2017-07-24 77 views
1

我有一个数据帧:转换大熊猫据帧要素元组

>>> df = pd.DataFrame(np.random.random((3,3))) 
>>> df 
      0   1   2 
0 0.732993 0.611314 0.485260 
1 0.935140 0.153149 0.065653 
2 0.392037 0.797568 0.662104 

什么对我来说是转换每个条目为2元组,与第一个元素从目前的数据框最简单的方法,而第二个元素从最后一列('2')?

即我想最后的结果是:

     0     1      2 
0 (0.732993, 0.485260) (0.611314, 0.485260) (0.485260, 0.485260) 
1 (0.935140, 0.065653) (0.153149, 0.065653) (0.065653, 0.065653) 
2 (0.392037, 0.662104) (0.797568, 0.662104) (0.662104, 0.662104) 
+0

你为什么要这么做?更具体地说,为什么你要使用熊猫,如果你想保持数据的格式熊猫本身不支持?您最好将数据保留为当前格式,并将算法更改为从第二列明确处理数据。 –

+0

例如,我想使用最后一列对所有其他列进行滚动回归。 AFAIK,这是不容易实现的([这里](https://stackoverflow.com/questions/44380068/pandas-rolling-regression-alternatives-to-looping),[here](https://stackoverflow.com/questions/21040766/python-pandas-rolling-apply-two-column-input-in-function),[here](https://stackoverflow.com/questions/19121854/using-rolling-apply-on-a-dataframe-对象)和[这里](https://stackoverflow.com/questions/21025821/python-custom-function-using-rolling-apply-for-pandas))。通过转换为元组,我有一个镜头。 – Zhang18

回答

3

由于PD版本0.20,您可以使用df.transform

In [111]: df 
Out[111]: 
    0 1 2 
0 1 3 4 
1 2 4 5 
2 3 5 6 

In [112]: df.transform(lambda x: list(zip(x, df[2]))) 
Out[112]: 
     0  1  2 
0 (1, 4) (3, 4) (4, 4) 
1 (2, 5) (4, 5) (5, 5) 
2 (3, 6) (5, 6) (6, 6) 

或者,使用df.apply另一种解决方案:

In [113]: df.apply(lambda x: list(zip(x, df[2]))) 
Out[113]: 
     0  1  2 
0 (1, 4) (3, 4) (4, 4) 
1 (2, 5) (4, 5) (5, 5) 
2 (3, 6) (5, 6) (6, 6) 

你也可以使用词典理解:

In [126]: pd.DataFrame({i : df[[i, 2]].apply(tuple, axis=1) for i in df.columns}) 
Out[126]: 
     0  1  2 
0 (1, 4) (3, 4) (4, 4) 
1 (2, 5) (4, 5) (5, 5) 
2 (3, 6) (5, 6) (6, 6) 
0

我同意Corley的评论,您最好将数据保留为当前格式,并将算法更改为从第二列明确处理数据。

但是,要回答您的问题,您可以定义一个函数来执行所需的操作并使用apply来调用它。

我不喜欢这个答案,这是丑陋的“应用”是一个“For循环”,你绝对是最好语法糖不使用这样的:

import numpy as np 
import pandas as pd 
df = pd.DataFrame(np.random.random((3,3))) 


df 
      0   1   2 
0 0.847380 0.897275 0.462872 
1 0.161202 0.852504 0.951304 
2 0.093574 0.503927 0.986476 


def make_tuple(row): 
    n= len(row) 
    row = [(x,row[n - 1]) for x in row] 
    return row 

df.apply(make_tuple, axis =1) 


0 (0.847379908309, 0.462871875315) (0.897274903359, 0.462871875315) 
1 (0.161202442072, 0.951303842798) (0.852504052133, 0.951303842798) 
2 (0.0935742441563, 0.986475692614) (0.503927404884, 0.986475692614) 
            2 
0 (0.462871875315, 0.462871875315) 
1 (0.951303842798, 0.951303842798) 
2 (0.986475692614, 0.986475692614)