Python的熊猫:如何把与“因素”一个数据帧成线性回归设计矩阵?(Python Pandas: h

2019-06-23 17:45发布

如果存储器servies我,R中有称为因子一种数据类型,其一个数据帧中使用时可以自动解压到一个回归矩阵设计的必要的列。 例如,含有真/假/可能值的因子将被转换成:

1 0 0
0 1 0
or
0 0 1

使用较低级回归代码的目的。 有没有办法使用熊猫库来实现类似的东西吗? 我看到有内大熊猫一些回归的支持,但因为我有自己的定制回归程序我在设计矩阵的异构数据结构(二维numpy的阵列或矩阵),支持真正感兴趣的映射背部和堡垒之间的numpy的对象和数据帧熊猫从其所源自的列。

更新:这是那种我想到的(例子来自熊猫手册)的异构数据数据矩阵的例子:

>>> df2 = DataFrame({'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],'c' : np.random.randn(7)})
>>> df2
       a  b         c
0    one  x  0.000343
1    one  y -0.055651
2    two  y  0.249194
3  three  x -1.486462
4    two  y -0.406930
5    one  x -0.223973
6    six  x -0.189001
>>> 

的“a”的列应该被转换成4个浮点列(尽管含义,仅存在四个独特的原子),则“B”列可以被转换为单个浮点柱,和“c”的列应在设计矩阵未修饰的最后一列。

谢谢,

那么setjmp

Answer 1:

有一个叫懦夫新的模块,解决了这个问题。 下面链接的快速启动解决恰好在上面的几行代码描述的问题。

  • http://patsy.readthedocs.org/en/latest/overview.html

  • http://patsy.readthedocs.org/en/latest/quickstart.html

下面是一个例子用法:

import pandas
import patsy

dataFrame = pandas.io.parsers.read_csv("salary2.txt") 
#salary2.txt is a re-formatted data set from the textbook
#Introductory Econometrics: A Modern Approach
#by Jeffrey Wooldridge
y,X = patsy.dmatrices("sl ~ 1+sx+rk+yr+dg+yd",dataFrame)
#X.design_info provides the meta data behind the X columns
print X.design_info

产生:

> DesignInfo(['Intercept',
>             'sx[T.male]',
>             'rk[T.associate]',
>             'rk[T.full]',
>             'dg[T.masters]',
>             'yr',
>             'yd'],
>            term_slices=OrderedDict([(Term([]), slice(0, 1, None)), (Term([EvalFactor('sx')]), slice(1, 2, None)),
> (Term([EvalFactor('rk')]), slice(2, 4, None)),
> (Term([EvalFactor('dg')]), slice(4, 5, None)),
> (Term([EvalFactor('yr')]), slice(5, 6, None)),
> (Term([EvalFactor('yd')]), slice(6, 7, None))]),
>            builder=<patsy.build.DesignMatrixBuilder at 0x10f169510>)


Answer 2:

import pandas
import numpy as np

num_rows = 7;
df2 = pandas.DataFrame(
                        {
                        'a' : ['one', 'one', 'two', 'three', 'two', 'one', 'six'],
                        'b' : ['x', 'y', 'y', 'x', 'y', 'x', 'x'],
                        'c' : np.random.randn(num_rows)
                        }
                      )

a_attribute_list = ['one', 'two', 'three', 'six']; #Or use list(set(df2['a'].values)), but that doesn't guarantee ordering.
b_attribute_list = ['x','y']

a_membership = [ np.reshape(np.array(df2['a'].values == elem).astype(np.float64),   (num_rows,1)) for elem in a_attribute_list ]
b_membership = [ np.reshape((df2['b'].values == elem).astype(np.float64), (num_rows,1)) for elem in b_attribute_list ]
c_column =  np.reshape(df2['c'].values, (num_rows,1))


design_matrix_a = np.hstack(tuple(a_membership))
design_matrix_b = np.hstack(tuple(b_membership))
design_matrix = np.hstack(( design_matrix_a, design_matrix_b, c_column ))

# Print out the design matrix to see that it's what you want.
for row in design_matrix:
    print row

我得到这样的输出:

[ 1.          0.          0.          0.          1.          0.          0.36444463]
[ 1.          0.          0.          0.          0.          1.         -0.63610264]
[ 0.          1.          0.          0.          0.          1.          1.27876991]
[ 0.          0.          1.          0.          1.          0.          0.69048607]
[ 0.          1.          0.          0.          0.          1.          0.34243241]
[ 1.          0.          0.          0.          1.          0.         -1.17370649]
[ 0.          0.          0.          1.          1.          0.         -0.52271636]

这样,第一列是该是“一”数据帧的位置的指示,第2栏是该是“2”,等等数据帧的位置的指示符。 列4和5是数据帧的位置的指标,分别那名“x”和“Y”,和最后一列仅仅是随机数据。



Answer 3:

熊猫0.13.1 2014年2月3日,有一个方法:

>>> pd.Series(['one', 'one', 'two', 'three', 'two', 'one', 'six']).str.get_dummies()
   one  six  three  two
0    1    0      0    0
1    1    0      0    0
2    0    0      0    1
3    0    0      1    0
4    0    0      0    1
5    1    0      0    0
6    0    1      0    0


Answer 4:

patsy.dmatrices在很多情况下工作良好。 如果仅仅有一个载体-一个pandas.Series -然后下面的代码可能会工作产生简并设计矩阵,并且在没有截距柱。

def factor(series):
    """Convert a pandas.Series to pandas.DataFrame design matrix.

    Parameters
    ----------
    series : pandas.Series
        Vector with categorical values

    Returns
    -------
    pandas.DataFrame
        Design matrix with ones and zeroes.

    See Also
    --------
    patsy.dmatrices : Converts categorical columns to numerical

    Examples
    --------
    >>> import pandas as pd
    >>> design = factor(pd.Series(['a', 'b', 'a']))
    >>> design.ix[0,'[a]']
    1.0
    >>> list(design.columns)
    ['[a]', '[b]']

    """
    levels = list(set(series))
    design_matrix = np.zeros((len(series), len(levels)))
    for row_index, elem in enumerate(series):
        design_matrix[row_index, levels.index(elem)] = 1
    name = series.name or ""
    columns = map(lambda level: "%s[%s]" % (name, level), levels)
    df = pd.DataFrame(design_matrix, index=series.index, 
                      columns=columns)
    return df


Answer 5:

import pandas as pd
import numpy as np

def get_design_matrix(data_in,columns_index,ref):
    columns_index_temp =  columns_index.copy( )
    design_matrix = pd.DataFrame(np.zeros(shape = [len(data_in),len(columns_index)-1]))
    columns_index_temp.remove(ref)
    design_matrix.columns = columns_index_temp
    for ii in columns_index_temp:
        loci = list(map(lambda x:x == ii,data_in))
        design_matrix.loc[loci,ii] = 1
    return(design_matrix)

get_design_matrix(data_in = ['one','two','three','six','one','two'],
                  columns_index = ['one','two','three','six'],
                  ref = 'one')


Out[3]: 
   two  three  six
0  0.0    0.0  0.0
1  1.0    0.0  0.0
2  0.0    1.0  0.0
3  0.0    0.0  1.0
4  0.0    0.0  0.0
5  1.0    0.0  0.0


文章来源: Python Pandas: how to turn a DataFrame with “factors” into a design matrix for linear regression?