将函数应用于 Pandas 数据框的每一行以创建两个新列 - python

我有一个熊猫DataFrame,st包含多列:

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 53732 entries, 1993-01-07 12:23:58 to 2012-12-02 20:06:23
Data columns:
Date(dd-mm-yy)_Time(hh-mm-ss)       53732  non-null values
Julian_Day                          53732  non-null values
AOT_1020                            53716  non-null values
AOT_870                             53732  non-null values
AOT_675                             53188  non-null values
AOT_500                             51687  non-null values
AOT_440                             53727  non-null values
AOT_380                             51864  non-null values
AOT_340                             52852  non-null values
Water(cm)                           51687  non-null values
%TripletVar_1020                    53710  non-null values
%TripletVar_870                     53726  non-null values
%TripletVar_675                     53182  non-null values
%TripletVar_500                     51683  non-null values
%TripletVar_440                     53721  non-null values
%TripletVar_380                     51860  non-null values
%TripletVar_340                     52846  non-null values
440-870Angstrom                     53732  non-null values
380-500Angstrom                     52253  non-null values
440-675Angstrom                     53732  non-null values
500-870Angstrom                     53732  non-null values
340-440Angstrom                     53277  non-null values
Last_Processing_Date(dd/mm/yyyy)    53732  non-null values
Solar_Zenith_Angle                  53732  non-null values
dtypes: datetime64[ns](1), float64(22), object(1)

我想基于将一个函数应用于数据框的每一行,为此数据框创建两个新列。我不想多次调用该函数(例如,通过执行两次单独的apply调用),因为它占用大量计算资源。我尝试通过两种方式来执行此操作,但它们都不起作用:

使用apply:

我编写了一个函数,该函数接受Series并返回我想要的值的元组:

def calculate(s):
    a = s['path'] + 2*s['row'] # Simple calc for example
    b = s['path'] * 0.153
    return (a, b)

尝试将此应用于DataFrame会出现错误:

st.apply(calculate, axis=1)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-248-acb7a44054a7> in <module>()
----> 1 st.apply(calculate, axis=1)

C:\Python27\lib\site-packages\pandas\core\frame.pyc in apply(self, func, axis, broadcast, raw, args, **kwds)
   4191                     return self._apply_raw(f, axis)
   4192                 else:
-> 4193                     return self._apply_standard(f, axis)
   4194             else:
   4195                 return self._apply_broadcast(f, axis)

C:\Python27\lib\site-packages\pandas\core\frame.pyc in _apply_standard(self, func, axis, ignore_failures)
   4274                 index = None
   4275 
-> 4276             result = self._constructor(data=results, index=index)
   4277             result.rename(columns=dict(zip(range(len(res_index)), res_index)),
   4278                           inplace=True)

C:\Python27\lib\site-packages\pandas\core\frame.pyc in __init__(self, data, index, columns, dtype, copy)
    390             mgr = self._init_mgr(data, index, columns, dtype=dtype, copy=copy)
    391         elif isinstance(data, dict):
--> 392             mgr = self._init_dict(data, index, columns, dtype=dtype)
    393         elif isinstance(data, ma.MaskedArray):
    394             mask = ma.getmaskarray(data)

C:\Python27\lib\site-packages\pandas\core\frame.pyc in _init_dict(self, data, index, columns, dtype)
    521 
    522         return _arrays_to_mgr(arrays, data_names, index, columns,
--> 523                               dtype=dtype)
    524 
    525     def _init_ndarray(self, values, index, columns, dtype=None,

C:\Python27\lib\site-packages\pandas\core\frame.pyc in _arrays_to_mgr(arrays, arr_names, index, columns, dtype)
   5411 
   5412     # consolidate for now
-> 5413     mgr = BlockManager(blocks, axes)
   5414     return mgr.consolidate()
   5415 

C:\Python27\lib\site-packages\pandas\core\internals.pyc in __init__(self, blocks, axes, do_integrity_check)
    802 
    803         if do_integrity_check:
--> 804             self._verify_integrity()
    805 
    806         self._consolidate_check()

C:\Python27\lib\site-packages\pandas\core\internals.pyc in _verify_integrity(self)
    892                                      "items")
    893             if block.values.shape[1:] != mgr_shape[1:]:
--> 894                 raise AssertionError('Block shape incompatible with manager')
    895         tot_items = sum(len(x.items) for x in self.blocks)
    896         if len(self.items) != tot_items:

AssertionError: Block shape incompatible with manager

然后,我将使用this question中显示的方法将apply返回的值分配给两个新列。但是,我什至无法做到这一点!如果我只返回一个值,则一切正常。

使用循环:

我首先创建了数据框的两个新列,并将它们设置为None:

st['a'] = None
st['b'] = None

然后遍历所有索引并尝试修改我在其中获得的这些None值,但是我所做的修改似乎没有用。也就是说,没有错误发生,但是DataFrame似乎没有被修改。

for i in st.index:
    # do calc here
    st.ix[i]['a'] = a
    st.ix[i]['b'] = b

我认为这两种方法都行得通,但都没有。那么,我在这里做错了什么?最好的,最“pythonic”和“pandaonic”方法是什么?

参考方案

为了使第一种方法可行,请尝试返回一个Series而不是一个元组(apply引发异常,因为它不知道如何将行粘合在一起,因为列数与原始框架不匹配)。

def calculate(s):
    a = s['path'] + 2*s['row'] # Simple calc for example
    b = s['path'] * 0.153
    return pd.Series(dict(col1=a, col2=b))

如果替换,则第二种方法应该可行:

st.ix[i]['a'] = a

与:

st.ix[i, 'a'] = a

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

Python Pandas:在多列上建立布尔索引 - python

尽管至少有关于如何在Python的pandas库中为DataFrame编制索引的two good教程,但我仍然无法在一个以上的列上找到一种优雅的SELECT编码方式。>>> d = pd.DataFrame({'x':[1, 2, 3, 4, 5], 'y':[4, 5, 6, 7, 8]}) >…

python pandas:按行对条件进行分组 - python

我有一个大的pandas数据框,试图从中形成一些行的对。我的df如下所示:object_id increment location event 0 1 d A 0 2 d B 0 3 z C 0 4 g A 0 5 g B 0 6 i C 1 1 k A 1 2 k B ... ... ... ... 对象ID描述特定的对象。增量是每次发生某事(跟踪订单)时…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

如何从'pandas.core.frame.DataFrame'中消除第一列 - python

我有以以下格式输出的代码。我应该如何删除第一列并可以将第二行的元素存储在列表中?输出类型为'pandas.core.frame.DataFrame'格式 speed lat lng 1 19.130506 12.616756 7.460664 2 63.595894 52.616838 7.460691 3 40.740044 72.616913 7.460…