2017-05-25 47 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