2017-12-13 6 views
0

내가 CSV는읽기와 파이썬에서 CSV 파일을 사용하여 3 팬더

Firstname Lastname  City  Province 
'Guy',  'Ouell', 'Brossard','QC' 
'Michelle', 'Balonne','Stittsville','ON' 
'Ben',  'Sluzing','Toronto','ON' 
'Theodora', 'Panapoulos','Saint-Constant','QC' 
'Kathleen', 'Mercier','St Johns','NL' 
... 

를 제출하고 난 열고 그것을 확인 :

df = pd.read_csv('a.csv') 
df.head(n=5) 

내가 열을 사용하려는 경우 I

문제 1 : 내가 첫 번째 열에 만 액세스 할 수 있으며 다른 열을 사용하려고 할 때 오류가 발생합니다.

for mis_column, mis_row in missing_df.iterrows(): 
    print(mis_row['Firstname']) 

나는 처음 이름을 모두 얻을하지만 난 모든 도시를 취득하고자 할 때, 예를 들어, 내가 참조 :

TypeError         Traceback (most recent call last) 
E:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 
    2482    try: 
-> 2483     return libts.get_value_box(s, key) 
    2484    except IndexError: 

pandas/_libs/tslib.pyx in pandas._libs.tslib.get_value_box 
(pandas\_libs\tslib.c:18843)() 

pandas/_libs/tslib.pyx in pandas._libs.tslib.get_value_box 
(pandas\_libs\tslib.c:18477)() 

TypeError: 'str' object cannot be interpreted as an integer 

During handling of the above exception, another exception occurred: 

KeyError         Traceback (most recent call last) 
<ipython-input-36-55ba81245685> in <module>() 
     1 
     2 for mis_column, mis_row in missing_df.iterrows(): 
----> 3  print(mis_row['City']) 
     4 
     5 

    E:\Anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key) 
     599   key = com._apply_if_callable(key, self) 
     600   try: 
    --> 601    result = self.index.get_value(self, key) 
     602 
     603    if not is_scalar(result): 

    E:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in 
    get_value(self, series, key) 
    2489      raise InvalidIndexError(key) 
    2490     else: 
    -> 2491      raise e1 
    2492    except Exception: # pragma: no cover 
    2493     raise e1 

    E:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 
    2475   try: 
    2476    return self._engine.get_value(s, k, 
    -> 2477  tz=getattr(series.dtype, 'tz', None)) 
    2478   except KeyError as e1: 
    2479    if len(self) > 0 and self.inferred_type in ['integer', 'boolean']: 

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value() 

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value() 

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() 

    pandas\_libs\hashtable_class_helper.pxi in 
    pandas._libs.hashtable.PyObjectHashTable.get_item() 

    pandas\_libs\hashtable_class_helper.pxi in 
    pandas._libs.hashtable.PyObjectHashTable.get_item() 

    KeyError: 'City' 

문제 2 :

for mis_column, mis_row in df.iterrows(): 
    if mis_row['Firstname'] == 'Guy': 
      print('A') 

가 인쇄되지 않습니다

미리 감사드립니다.

+0

헤더 행이 쉼표로 구분되어 있지 않은 것 같습니다. 의도 한 것입니까? –

+0

열 이름을 확인하십시오, 거기에 흰 공백이 있다고 생각하십시오 – Wen

+0

원본 CSV에서 헤더는 쉼표로 구분됩니다. –

답변

0

CSV 헤더를 쉼표로 구분하십시오. 당신의 CSV 주위에 공백이 있기 때문에 당신이 다음뿐만 아니라 작은 따옴표를 제거하려면 다음과 같이

Firstname, Lastname,  City,  Province 
'Guy',  'Ouell', 'Brossard','QC' 
'Michelle', 'Balonne','Stittsville','ON' 
'Ben',  'Sluzing','Toronto','ON' 
'Theodora', 'Panapoulos','Saint-Constant','QC' 
'Kathleen', 'Mercier','St John's','NL' 

, 당신은 건너 뛰어 dataframe에

df = pd.read_csv('<your_input>.csv', skipinitialspace=True) 

을 읽을 수

df = pd.read_csv('<your_input>.csv', skipinitialspace=True, quotechar="'") 

>>> df 
    Firstname Lastname   City Province 
0  Guy  Ouell  Brossard  QC 
1 Michelle  Balonne  Stittsville  ON 
2  Ben  Sluzing   Toronto  ON 
3 Theodora Panapoulos Saint-Constant  QC 
4 Kathleen  Mercier  St Johns'  NL 


>>> import pandas as pd 
>>> df = pd.read_csv('test2.csv', skipinitialspace=True, quotechar="'") 
>>> df 
    Firstname Lastname   City Province 
0  Guy  Ouell  Brossard  QC 
1 Michelle  Balonne  Stittsville  ON 
2  Ben  Sluzing   Toronto  ON 
3 Theodora Panapoulos Saint-Constant  QC 
4 Kathleen  Mercier  St Johns'  NL 
>>> for mis_column, mis_row in df.iterrows(): 
...  if mis_row['Firstname'] == 'Guy': 
...    print('A') 
... 
A 
>>> 
+0

첫 번째 문제가 해결되었습니다. 두 번째 문제에 대한 제안이 있습니까? –

+0

내 답변에 제시된 제안을 적용한 후에 자연스럽게 두 번째 문제는 없어야합니다! 그렇지 않니? –

+0

생각해 보았지만 여전히 존재합니다. –

관련 문제