【问题标题】:Keep pandas structure with numpy/scikit functions使用 numpy/scikit 函数保持 pandas 结构
【发布时间】:2013-01-26 14:56:22
【问题描述】:

我正在使用来自 pandas 的出色的 read_csv()function,它给出:

In [31]: data = pandas.read_csv("lala.csv", delimiter=",")

In [32]: data
Out[32]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 12083 entries, 0 to 12082
Columns: 569 entries, REGIONC to SCALEKER
dtypes: float64(51), int64(518)

但是当我从 scikit-learn 应用一个函数时,我会丢失有关列的信息:

from sklearn import preprocessing
preprocessing.scale(data)

给出 numpy 数组。

有没有办法在不丢失信息的情况下将 scikit 或 numpy 函数应用于 DataFrame?

【问题讨论】:

    标签: python pandas numpy scikit-learn


    【解决方案1】:

    一种(有点天真)的方法是分别存储数据框的结构,即它的列和索引,然后从您的预处理结果创建一个新的数据框,如下所示:

    In [15]: data = np.zeros((2,2))
    
    In [16]: data
    Out[16]: 
    array([[ 0.,  0.],
           [ 0.,  0.]])
    
    In [17]: from pandas import DataFrame
    
    In [21]: df  = DataFrame(data, index = ['first', 'second'], columns=['c1','c2'])
    
    In [22]: df
    Out[22]: 
            c1  c2
    first    0   0
    second   0   0
    
    In [26]: i = df.index
    
    In [27]: c = df.columns
    
    # generate new data as a numpy array    
    In [29]: df  = DataFrame(np.random.rand(2,2), index=i, columns=c)
    
    In [30]: df
    Out[30]: 
                  c1        c2
    first   0.821354  0.936703
    second  0.138376  0.482180
    

    正如您在Out[22] 中看到的,我们从数据框开始,然后在In[29] 中,我们将一些新数据放入框内,而行和列保持不变。我假设您的预处理将not 打乱数据的行/列。

    【讨论】:

      【解决方案2】:

      这可以通过将返回的数据包装在一个数据框中来完成,其中包含indexcolumns 信息。

      import pandas as pd
      pd.DataFrame(preprocessing.scale(data), index = data.index, columns = data.columns) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-21
        • 2018-11-02
        • 2021-03-25
        • 2017-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        相关资源
        最近更新 更多