2017-05-25 54 views
0

我想在单个if语句中使用2个连续的行,在数据帧的for循环中使用迭代'i'但它显示执行错误。我的代码 -if语句中的错误,同时使用迭代元素

import pandas as pd 

data = pd.read_csv("C:\\Users\\Abhi\\Desktop\\Book1.csv",low_memory=False) 

data['DV+']=pd.Series("",index=data.index) 

for j in range(len(data.index)): 

    if (data['Customer_Site_ID'][j]==data['Customer_Site_ID'][j+1] and (data['DCVolt'][j]-data['DCVolt'][j+1])>0.2 and min(data['BatDC'][j],data['BatDC'][j+1])>0 and (data['BatDC'][j]-data['BatDC'][j+1])<5): 
     data['DV+'][j]=1 
    else: 
     data['DV+'][j]=0 
data.to_csv("C:\\Users\\Abhi\\Desktop\\book11.csv", index=False,encoding='utf-8') 

错误我m到处是 -

Traceback (most recent call last): 

    File "<ipython-input-1-0469458ba48f>", line 1, in <module> 
    runfile('C:/Users/Abhi/Desktop/newfeed.py', wdir='C:/Users/Abhi/Desktop') 

    File "C:\Users\Abhi\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile 
    execfile(filename, namespace) 

    File "C:\Users\Abhi\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile 
    exec(compile(f.read(), filename, 'exec'), namespace) 

    File "C:/Users/Abhi/Desktop/newfeed.py", line 15, in <module> 
    if (data['Customer_Site_ID'][j]==data['Customer_Site_ID'][j+1] and (data['DCVolt'][j]-data['DCVolt'][j+1])>0.2 and min(data['BatDC'][j],data['BatDC'][j+1])>0 and (data['BatDC'][j]-data['BatDC'][j+1])<5): 

    File "C:\Users\Abhi\Anaconda3\lib\site-packages\pandas\core\series.py", line 603, in __getitem__ 
    result = self.index.get_value(self, key) 

    File "C:\Users\Abhi\Anaconda3\lib\site-packages\pandas\indexes\base.py", line 2169, in get_value 
    tz=getattr(series.dtype, 'tz', None)) 

    File "pandas\index.pyx", line 98, in pandas.index.IndexEngine.get_value (pandas\index.c:3557) 

    File "pandas\index.pyx", line 106, in pandas.index.IndexEngine.get_value (pandas\index.c:3240) 

    File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:4279) 

    File "pandas\src\hashtable_class_helper.pxi", line 404, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:8564) 

    File "pandas\src\hashtable_class_helper.pxi", line 410, in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:8508) 

KeyError: 15 

PLZ让我知道正确的方法来访问数据帧行的值使用的(任何)循环迭代元素。

回答

0

我会推荐大熊猫(0.20.1)文档,特别是关于索引和选择数据的this部分。

您可以使用.loc以及其他选项访问数据框中的行值。

>>> data = pd.DataFrame({'column':[i for i in range(15)]}) 

>>> for i in range(len(data)): 
...  print(data.loc[i, 'column']) 
... 
0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14