熊猫地图列到位

时间:2016-03-16 07:51:50

标签: python numpy pandas

我花了一些时间在谷歌上搜索并没有找到答案这个简单的问题:如何在适当的位置映射Pandas数据帧列? 说,我有以下df:

In [67]: frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])

In [68]: frame
Out[68]: 
               b         d         e
Utah   -1.240032  1.586191 -1.272617
Ohio   -0.161516 -2.169133  0.223268
Texas  -1.921675  0.246167 -0.744242
Oregon  0.371843  2.346133  2.083234

我想为b列的每个值添加1。我知道我可以这样做:

In [69]: frame['b'] = frame['b'].map(lambda x: x + 1)

或者像那样 - AFAIK mapapplySeries的背景下没有区别(除了map也可以接受dictSeries) - 如果我错了,请纠正我:

In [71]: frame['b'] = frame['b'].apply(lambda x: x + 1)

但我不想两次指定'b'。相反,我想做类似的事情:

frame['b'].map(lambda x: x + 1, inplace=True)

有可能吗?

2 个答案:

答案 0 :(得分:5)

class Text(object):

    def __init__(self):
        self._color = "blue"
        self._length = 12

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, value):
        self._color = value

    @property
    def length(self):
        return self._length

    @length.setter
    def length(self, value):
        self._length = value

编辑添加:

如果这是一个仲裁函数,并且您确实需要在适当的位置应用,则可以在pandas周围编写一个薄的包装来处理它。就个人而言,我无法想象你不需要使用标准实现是否至关重要的时候(除非你写了一大堆代码并且可能不愿意写下额外的字符或许? )

frame
Out[6]: 
               b         d         e
Utah   -0.764764  0.663018 -1.806592
Ohio    0.082226 -0.164653 -0.744252
Texas   0.763119  1.492637 -1.434447
Oregon -0.485245 -0.806335 -0.008397

frame['b'] +=1

frame
Out[8]: 
               b         d         e    
Utah    0.235236  0.663018 -1.806592
Ohio    1.082226 -0.164653 -0.744252
Texas   1.763119  1.492637 -1.434447
Oregon  0.514755 -0.806335 -0.008397

给予:

from pandas import DataFrame
import numpy as np

class MyWrapper(DataFrame):
    def __init__(self, *args, **kwargs):
        super(MyWrapper,self).__init__(*args,**kwargs)

    def myapply(self,label, func):
        self[label]= super(MyWrapper,self).__getitem__(label).apply(func)


df =  frame = MyWrapper(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print df
df.myapply('b', lambda x: x+1)
print df

显然,这是一个非常小的例子,希望能为您揭示一些感兴趣的方法。

答案 1 :(得分:1)

您可以使用add

In [2]: import pandas as pd

In [3]: import numpy as np

In [4]: frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=
   ...: ['Utah', 'Ohio', 'Texas', 'Oregon'])

In [5]: frame.head()
Out[5]:
               b         d         e
Utah   -1.165332 -0.999244 -0.541742
Ohio   -0.319887  0.199094 -0.438669
Texas  -1.242524 -0.385092 -0.389616
Oregon  0.331593  0.505496  1.688962

In [6]: frame.b.add(1)
Out[6]:
Utah     -0.165332
Ohio      0.680113
Texas    -0.242524
Oregon    1.331593
Name: b, dtype: float64

In [7]: