I've frequently used the account, customer level data. Sometimes there's an requests to make the application table into customer level data. In this case, we can use the python group by but I should the account level data with priority. For example, customers may apply multiple Credit Card and I should tag the account like '1st', '2nd', '3rd'.

 In SAS, Impala's world, it's not so difficult make this but there's no function in python.

 

 I've already searched the similar function in Python but couldn't find the solution. Thus I've made the simple code to generate the order like below.

If you find the proper solution except the above code, please leave a message.

반응형

 다른 방법들도 몇 개 있었는데, User Warning이 나서 아래와 같은 방법을 써야 한다.

 

df = df.rename(columns=str.lower)

df.head()

반응형

 파이썬으로 데이터를 핸들링하면서 가장 고민했던 부분을 해결해 주었던 정말 아름다운 글이다.

이렇게 되는 것을 몰라서 한참을 고민했는데 실제 이 정도만 되어도 왠만한 자료들은 Pandas로만으로도 충분히 만들 수 있다. 물론 중간에 코드를 결합하거나 하는 복잡한 것을 한 방에 처리해주는 SQL은 안되지만 말이지. 어찌 되었거나 SQL을 못쓴다고 해도 이런 대체물이 있으니까 다행이라고 해야 할까?

 R dplyr 배우기 싫어서 sqldf로 모두 떡칠해서 썼던 것이 얼마전인데, 참 사람 일은 모를 일이다.

 

 

https://keytodatascience.com/groupby-pandas-python

반응형

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import os

import sys

import scipy

from contextlib import suppess

imoport time

from datetime import datetime, timedelta, date

from dateutil.relativedelta import relativedelta

import tensorflow

from tensorflow import keras

from tensorflow.keras import layers

 

 

반응형

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from contextlib import suppress

import os

import sys

 

 

## Put path in which to save

filename="test.csv"

path_file=ow.getcwd() + "/" + filename

path_file

 

## 빈 파일 만들기

!time touch path_file

 

# 파일 전달하기

!time hdfs dfs -ut test.csv /user/kp19983

 

# drop the table

with suppress(TypeError) : pd.read_sql("""DROP TABLE IF EXISTS db.temp""", conn)

 

## Create table

query="""

create table db.temp(salaried int,

                                    code_group VARCHAR(20),

                                    cnt int)

ROW FORMAT DELIMITED

FIELDS TERMINATED BY ','

TBLPROPERTIES("skip.header.line.count"="1");

"""

pd.read_sql(query, conn)

 

## Load the data into table

with suppress(TypeError) : pd.read_sql("""

LOAD DATA inpath 'hdfs//koreaserver/data/db/users/temp.csv' INTO TABLE db.temp;

""", conn)

 

## 테이블 잘 생성되었는지 확인해 보기

query="""

select *

from db.temp

"""

a=pd.read_sql(query, conn)

 

a[:5]

 

반응형

 

from datetime import datetime, timedelta, date

from dateutil.relativedelta import relativedelta

import time

 

## Impala table을 이용해서 Python data frame에 각종 날짜 정보를 저장한다.

## 저장된 DataFrame 이름은 cald

 

date_param={} ## date parameter dictionary

 

def asgn():

    for col in cald.columns:

        for in in range(0, len(cald)):

            a=col+ str(i) ## 컬럼명 + 일련번호

            if cald.loc[i, col] != '' ## NaN, Null인 경우 Dictionary에 값을 저장하지 않는다.

                date_param[a]=cald.loc[i, col]

asgn()

 

date_param['yyyymm0']

'202104'

 

## Python에서 수기로 계산하는 값들은 바로 Dictionary에 저장한다.

date_param['curr']=cald.loc[0, 'curr']

date_param['d30']=(pd.to_datetime(cald.loc[0, 'curr'], format='%Y%m%d') + relativedelta(days=-30)).strftime('%Y%m%d')

date_param['d60']=(pd.to_datetime(cald.loc[0, 'curr'], format='%Y%m%d') + relativedelta(days=-60)).strftime('%Y%m%d')

date_param['d90']=(pd.to_datetime(cald.loc[0, 'curr'], format='%Y%m%d') + relativedelta(days=-00)).strftime('%Y%m%d')

date_param['d180']=(pd.to_datetime(cald.loc[0, 'curr'], format='%Y%m%d') + relativedelta(days=-180)).strftime('%Y%m%d')

 

print(date_param['d30'])

반응형

'Python, PySpark' 카테고리의 다른 글

Python 주요 라이브러리  (0) 2021.05.13
Python에서 하둡으로 자료 보내기  (0) 2021.05.13
Python - 날짜 관련 함수들  (0) 2021.05.07
Jupyter Notebook 명령어 및 옵션들  (0) 2021.05.06
Python 기본 함수들  (0) 2021.05.06

+ Recent posts