在迭代过程中查找熊猫数据框的当前值

时间:2019-04-12 21:26:26

标签: python-3.x pandas

因此,我想根据每行的值替换熊猫数据框中一列的值。它类似于归一化,只是我只需要整数值。

df.head()
    Sampling Date   NO2     RSPM/PM10   SO2     Class
0   2006-01-03  30.8    116.0   6.7     NaN
1   2006-01-06  48.0    145.0   10.5    NaN
2   2006-01-12  44.5    166.0   8.5     NaN
3   2006-01-17  44.3    144.0   9.5     NaN
4   2006-01-20  51.3    113.0   7.3     NaN
def normalizeValues(type, val):
    if type=='NO2':
        if val>=0 and val<=100:
            return 1
        elif val>=101 and val<=350:
            return 2
        else:
            return 3
df['NO2']=normalizeValues("NO2",df['NO2'])

我期待中

df.head()
    Sampling Date   NO2     RSPM/PM10   SO2     Class
0   2006-01-03  1   116.0   6.7     NaN
1   2006-01-06  1   145.0   10.5    NaN
2   2006-01-12  1   166.0   8.5     NaN
3   2006-01-17  1   144.0   9.5     NaN
4   2006-01-20  1   113.0   7.3     NaN

但是,相反,我得到一个错误

ValueError                                Traceback (most recent call last)
<ipython-input-18-31b35122d724> in <module>()
----> 1 df['NO2']=normalizeValues("NO2",df.NO2)

<ipython-input-17-99deab871e75> in normalizeValues(type, val)
      1 def normalizeValues(type, val):
      2     if type=='NO2':
----> 3         if val>=0 and val<=100:
      4             return 1
      5         elif val>=101 and val<=350:

/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in __nonzero__(self)
    953         raise ValueError("The truth value of a {0} is ambiguous. "
    954                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 955                          .format(self.__class__.__name__))
    956 
    957     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

2 个答案:

答案 0 :(得分:0)

您可以使用类似这样的内容-

Dim rs As DAO.Recordset
Dim OlApp As Object
Dim OlMail As Object

Set OlApp = CreateObject("Outlook.Application")
Set OlMail = OlApp.CreateItem(0)
Set rs = CurrentDb.OpenRecordset("SELECT Email FROM [EmailList]")

With OlMail    
    Do While rs.EOF = False
        .Recipients.Add rs!Email
        rs.MoveNext
    Loop
    .Subject = "MOC"
    .HTMLbody = "<a href=""X:\MOC Training.accdb"">Click Here for Training</a><br>"
    .Display
End With
Set OlMail = Nothing
Set OlApp = Nothing

答案 1 :(得分:0)

IIUC,您可以使用pandas.cut获得相同的效果。这是经过优化的,并且比迭代要快得多:

import numpy as np

bins = [0, 100, 350, np.inf]
df['NO2'] = pd.cut(df['NO2'], bins=bins, labels=[1, 2, 3], include_lowest=True)