반응형

https://pandas.pydata.org/pandas-docs/stable/index.html

 

pandas documentation — pandas 2.2.1 documentation

API reference The reference guide contains a detailed description of the pandas API. The reference describes how the methods work and which parameters can be used. It assumes that you have an understanding of the key concepts.

pandas.pydata.org

 

Community tutorials — pandas 2.2.1 documentation

 

pandas.pydata.org

 

반응형
반응형


error : Cannot interpret '<attribute 'dtype' of 'numpy.generic' objects>' as a data type 

 

    발생하면  pandas를 업그레이드 하라. 

 

pip install numpy --upgrade
pip install pandas --upgrade
반응형
반응형

pip install matplotlib

matplotlib 3.7.2

https://pypi.org/project/matplotlib/

 

matplotlib

Python plotting package

pypi.org

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.

Check out our home page for more information.

Matplotlib produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, Python/IPython shells, web application servers, and various graphical user interface toolkits.

Install

See the install documentation, which is generated from /doc/users/installing/index.rst

Contribute

You've discovered a bug or something else you want to change - excellent!

You've worked out a way to fix it -- even better!

You want to tell us about it -- best of all!

Start at the contributing guide!

반응형
반응형

Pandas Tutorial

https://www.w3schools.com/python/pandas/default.asp

 

Pandas Tutorial

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

Pandas is a Python library.

Pandas is used to analyze data.

 

https://pypi.org/project/pandas/

pip install pandas

 

 

pandas

Powerful data structures for data analysis, time series, and statistics

pypi.org

 

Pandas   http://bigdata.dongguk.ac.kr/lectures/Python/_book/pandas.html#pandas-dataframe

  • 데이터 처리와 분석을 위한 라이브러리
  • 행과 열로 이루어진 데이터 객체를 만들어 다룰 수 있음
  • 대용량의 데이터들을 처리하는데 매우 편리
  • pandas 자료구조
    • Series: 1차원
    • DataFrame: 2차원
    • Panel: 3차원
  • pandas 로딩
    • import numpy as np # 보통 numpy와 함께 import
    • import pandas as pd
""" Pandas Tutorial
https://www.w3schools.com/python/pandas/default.asp

Pandas is a Python library.
Pandas is used to analyze data.
"""

#import pandas
import pandas as pd #Now the Pandas package can be referred to as pd instead of pandas.


mydataset = {
  'cars': ["BMW", "Volvo", "Ford"],
  'passings': [3, 7, 2]
}

myvar = pd.DataFrame(mydataset)

print(myvar)


import pandas as pd
print(pd.__version__)
반응형
반응형

[python] 공공데이터 OPEN API의 xml 을 DataFrame으로 변환하기(feat. 코로나 확진자 수)

 

 

https://greendreamtrre.tistory.com/268

 

Python (파이썬) 공공데이터 수집 (Open API - XML)

공공데이터포털의 특징은 자료를 활용을 요약하자면 1. 회원 가입 후 '사용자 인증키'를 생성해야한다. 2. 이후 원하는 데이터를 '활용 신청'을 해서 승인이 떨어지고 활용 권한을 획득해야한다.

greendreamtrre.tistory.com

 

# 모듈 import
import requests
import pprint


#인증키 입력
encoding = '발급받은 인코딩 인증키를 복사하여 붙여넣기 해 주세요.'
decoding = '발급받은 디코딩 인증키를 복사하여 붙여넣기 해 주세요.'

#url 입력
url = 'http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19SidoInfStateJson'
params ={'serviceKey' : decoding , 'pageNo' : '1', 'numOfRows' : '10', 'startCreateDt' : '2020', 'endCreateDt' : '20211103' }

response = requests.get(url, params=params)

# xml 내용
content = response.text

# 깔끔한 출력 위한 코드
pp = pprint.PrettyPrinter(indent=4)
#print(pp.pprint(content))

### xml을 DataFrame으로 변환하기 ###
from os import name
import xml.etree.ElementTree as et
import pandas as pd
import bs4
from lxml import html
from urllib.parse import urlencode, quote_plus, unquote

## 각 컬럼 값 ## (포털 문서에서 꼭 확인하세요)
"""
SEQ : 게시글번호(국내 시도별 발생현황 고유값)
CREATE_DT: 	등록일시분초
DEATH_CNT: 	사망자 수
GUBUN: 	시도명(한글)
GUBUN_CN: 	시도명(중국어)
gubunEn: 시도명(영어)
INC_DEC: 전일대비 증감 수
ISOL_CLEAR_CNT: 격리 해제 수
QUR_RATE: 10만명당 발생률
STD_DAY: 기준일시
UPDATE_DT: 수정일시분초
DEF_CNT: 확진자 수
ISOL_ING_CNT: 격리중 환자수
OVER_FLOW_CNT: 해외유입 수
LOCAL_OCC_CNT: 지역발생 수

""" 

#bs4 사용하여 item 태그 분리

xml_obj = bs4.BeautifulSoup(content,'lxml-xml')
rows = xml_obj.findAll('item')
print(rows)
"""
# 컬럼 값 조회용
columns = rows[0].find_all()
print(columns)
"""

# 각 행의 컬럼, 이름, 값을 가지는 리스트 만들기
row_list = [] # 행값
name_list = [] # 열이름값
value_list = [] #데이터값

# xml 안의 데이터 수집
for i in range(0, len(rows)):
    columns = rows[i].find_all()
    #첫째 행 데이터 수집
    for j in range(0,len(columns)):
        if i ==0:
            # 컬럼 이름 값 저장
            name_list.append(columns[j].name)
        # 컬럼의 각 데이터 값 저장
        value_list.append(columns[j].text)
    # 각 행의 value값 전체 저장
    row_list.append(value_list)
    # 데이터 리스트 값 초기화
    value_list=[]

#xml값 DataFrame으로 만들기
corona_df = pd.DataFrame(row_list, columns=name_list)
print(corona_df.head(19)) 

#DataFrame CSV 파일로 저장
corona_df.to_csv('corona_kr.csv', encoding='utf-8-sig')
반응형
반응형

[python] Pandas 데이터프레임(Dataframe)을 txt로 저장하기

 

.to_csv를 이용하면 된다. 

import pandas as pd



#dictionary형 자료형을 판다스 데이터프레임으로 만들어줌 
#orient=index를 넣어야 행으로 쭉 나열이 됨 
df=pd.DataFrame.from_dict(count, orient='index')

df.to_csv('bigKeyword_all.txt')
df.head(100).to_csv('bigKeyword_top100.txt')


# Dataframe의 내용을 csv로 생성
## DataFrame.to_csv(path_or_buf=None, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w'
#                    , encoding=None, compression='infer', quoting=None, quotechar='"', line_terminator=None, chunksize=None, date_format=None
#                    , doublequote=True, escapechar=None, decimal='.', errors='strict')
df.to_csv('output/word_ex_note_1.csv', index = False, header=False, line_terminator=False, encoding='utf-8-sig')
df.head(100).to_csv('output/word_ex_note_100.csv', header=False, line_terminator=False, encoding='utf-8-sig')
df.to_csv('output/word_ex_note_1.txt', sep = '\t', index = False,header=False, line_terminator=False, encoding='utf-8-sig')

 

 

반응형
반응형

   
## 시간 표시  ##################################### 
import time
import datetime
now = datetime.datetime.now()

timeserise = time.time()
timeserise = str(int(timeserise))
print(timeserise)
print(now)
#################################################  

#작업하는 경로(위치)가 어디인지 확인
print(os.getcwd())

prePath = "./Project/DataCrawring/"


# CSV 파일로 저장
def dfToCsv(movie_df, num):
    try:
        # 파일이 존재하면 누적저장 mode='a', header=False
        if not os.path.exists(prePath  +'input/movie_data'+str(num) +'.csv'): 
            #movie_df.to_csv((prePath  +'input/movie_data'+str(num) +'.csv'),   header=False, line_terminator=False, encoding='utf-8-sig')        
            movie_df.to_csv((prePath  +'input/movie_data'+str(num) +'.csv'),   index=False, mode='w', header=True, line_terminator=False, encoding='utf-8-sig')
            print("First Save Success~~~ ")        
        else:
            movie_df.to_csv((prePath  +'input/movie_data'+str(num) +'.csv'),   index=False, mode='a', header=False, line_terminator=False, encoding='utf-8-sig')
            print("Add Save Success~~~ ")        
    except:
        print("Error - dfToCsv.....")

pandas 결과값을 csv 파일 형식으로 누적해서 저장하기: to_csv

 

to_csv Append Mode 사용하기

import pandas as pd
import os

# 샘플 데이터 생성
soda = {'상품명': ['콜라', '사이다'], '가격': [2700, 2000]}
df = pd.DataFrame(soda)

# .to_csv 
# 최초 생성 이후 mode는 append
if not os.path.exists('output.csv'):
    df.to_csv('output.csv', index=False, mode='w', encoding='utf-8-sig')
else:
    df.to_csv('output.csv', index=False, mode='a', encoding='utf-8-sig', header=False)

encoding='utf-8' 사용시 한글깨짐 현상이 발생하여, 'utf-8-sig'를 사용하였습니다. utf-8-sig에 관한 더 자세한 내용은 https://stackoverflow.com/questions/25788037/pandas-df-to-csvfile-csv-encode-utf-8-still-gives-trash-characters-for-min를 참고해주세요.

 

 

 

반응형
반응형

pandas documentation - python

 

https://pandas.pydata.org/docs/index.html

 

pandas documentation — pandas 1.4.1 documentation

The reference guide contains a detailed description of the pandas API. The reference describes how the methods work and which parameters can be used. It assumes that you have an understanding of the key concepts.

pandas.pydata.org

 

반응형

+ Recent posts