DataFrame 자주쓰는 문법 정리

<문법>/파이썬|2022. 3. 28. 16:53
반응형

초기세팅

import pandas as pd
import glob
import pickle
import matplotlib.pyplot as plt

pd.set_option('display.max_columns', None) # dataframe 잘림없이 출력
pd.set_option('display.max_rows', None)
pd.set_option('display.max_seq_items', None) # 리스트 잘림없이 출력
pd.options.display.float_format = '{:.5f}'.format  # e, 지수없이 출력
pd.set_option('display.max_colwidth', -1) #pd로 볼때 ...없이 출력
import warnings # warning 무시
warnings.filterwarnings('ignore')
pd.set_option('mode.chained_assignment',  None) # SettingWithCopyWarning 경고끄기

 

< 행열 이름바꾸기 >

더보기

# 행이름/열이름 변경 (index,columns 통으로 변경)

# 행 인덱스, 열 이름 변경하기
df.index=['학생1', '학생2']
df.columns=['연령','남녀','소속']

 

# 행이름/열이름 원래있는걸 다른이름으로 바꿔주기 (index,columns 이미있는걸 변경)

# 열 이름을 변경한다
df.rename(columns={'연령':'나이', '남녀':'성별', '소속':'학교'}, inplace=True)
# 행 인덱스를 변경한다
df.rename(index={'학생1':'준서', '학생2':'예은'}, inplace=True)

<행열 삭제>

더보기

열삭제 

del df['A']

df.drop(["B", "C"], axis=1)
df.drop(columns=["B", "C"],inplace=True)
df.pop("A") # A열만 반환해준다음,df확인해보면 A 빠져있을것

 

행삭제

df = df.drop(index=0, axis=0)
df = df.drop(index=[0, 1, 2], axis=0)
new_iris = iris.drop([1,2])
df.drop(["B", "C"], axis=0)

# 특정문자(save_fig2리스트에저장) 가 포함된 열 삭제
for i in save_fig2:
    print(i)
    df2 = df2[df2.columns.drop(list(df2.filter(regex=i)))]

<행열 타입 바꾸기>

더보기
df = df.astype({'시가':'int'}) # 특정열만 바꿔주기

<판다스 오름차순>

더보기
df['a'].sort_values()   # 작은수부터
df['a'].sort_values(ascending=False)   # 큰수부터

# 이건 해당 열에 맞춰서 모든 dataframe순서바꿈 / 큰수부터
per_model = per_model.sort_values(by=["noclust"], ascending=[False])

<데이터프레임 저장/불러오기>

더보기
# 저장
df.to_csv('./df.csv')
# 불러오기
df = pd.read_csv('./Data.csv')

<데이터프레임 잘리는거없이 전부 출력>

더보기
import warnings #dataframe 전체다출력
warnings.filterwarnings('ignore')
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

<리스트 잘리는거없이 모두 출력 - dataframe columns너무많을때 잘림>

더보기
pd.set_option('display.max_seq_items', None)  # 리스트 잘리는거없이 전부 출력
df.columns

<데이터프레임 생성(컬럼,인덱스 지정)>

더보기
Data_T = pd.DataFrame(index = list(index_list),columns = list(columns_list))

<아래 행추가>

더보기
Total_latency.loc[len(Total_latency)] = [column1_value, column2_value]

< untilied:0 없이 / 저장한 포맷그대로 열기>

더보기
epoch_latency = pd.read_csv('epoch_latency.csv',index_col = 0)

< 얕은 복사>

더보기
import copy
b = copy.copy(a)

< index 재정렬 >

더보기
  df = df.reset_index(drop=True)

<특정열 제외하고 보기>

더보기
DATA[DATA.columns.difference(['Target_Instance', 'Target_latency'])].head()

< 특정행 제거>

더보기
gojung2 = gojung.drop(['CLOUD','GPU TYPE'])

 

<데이터프레임 type 바꾸기>

더보기
df.astype('float')

< 데이터프레임 오른쪽에 붙이기>

더보기
new = pd.concat([a, b],axis=1)

< 데이터프레임 아래에 붙이기>

더보기
pd.concat([df1, df2], axis = 0)

< replace >

더보기
df.replace(0, 5)  # 0을 5로 바꿔주기

 

 

< 원핫인코딩 >

더보기
pd.get_dummies(data['Embarked'])

 

< 쥬피터 동시에 여러개 실행 >

더보기
from multiprocessing import Pool
if __name__ == '__main__':
    with Pool(len(devide_3000)+1) as p:
        p.map(MADE_HN, devide_3000)
def MADE_HN(N):
	블라블라

< 리스트 차집합, 뺼셈 >

더보기
complement = list(set(lst1) - set(lst2))

< 얕은 복사 >

더보기
CROSS_column_DATA_scaled = CROSS_column_DATA.copy()

< 리눅스 파일복사>

더보기
cp -r /tf/Yoonseo/Github/DCGMI/dcgm/a100 /tf/Yoonseo/Github/DCGMI2/DATA/
# cp -r 복사할파일 복사해줄위치

< 상관관계 3가지 >

더보기
corr_kendall_DATA_NEW = DATA_NEW.corr(method="kendall")  # kendall pearson spearman
spearman_DATA_NEW = DATA_NEW.corr(method="spearman")  # kendall pearson spearman
pearson_DATA_NEW = DATA_NEW.corr(method="pearson")  # kendall pearson spearman

< 보기편하게 모아서 보기 >

더보기
show_data.groupby(['train','instance']).first()

< 피클파일 열기 >

더보기
with open('../DATA/raw-data/exp09/g5.xlarge/times-EC2-128-InceptionV3.pickle', 'rb') as f: df = pickle.load(f)

< 교집합 >

더보기
intersection = list(set(lst1) & set(lst2))

< 특정문자 포함 파일 지우기>

더보기
sudo rm -f *.csv

<여러개파일 zip>

더보기

 

zip zipfile.zip 파일1 파일2 파일3

< 행값 합 구하기 >

더보기
df.sum(axis=1)

< time >

더보기
start = time.time()
math.factorial(100000)
end = time.time()

print(f"{end - start:.5f} sec")

< Lambda 예제 >

더보기
# lambda 매개변수 : 표현식
# map(함수, 리스트)
# reduce(함수, 시퀀스)
# filter(함수, 리스트)

##################################################
>>> (lambda x,y: x + y)(10, 20)
30
>>> plus_ten = lambda x: x + 10
>>> plus_ten(1)
11
##################################################
>>> list(map(lambda x: x ** 2, range(5)))    
[0, 1, 4, 9, 16]
##################################################
>>> from functools import reduce   
>>> reduce(lambda x, y: x + y, [0, 1, 2, 3, 4])
10
>>> reduce(lambda x, y: y + x, 'abcde')
'edcba'
##################################################
>>> list(filter(lambda x: x < 5, range(10))) 
[0, 1, 2, 3, 4]
>>> list(filter(lambda x: x % 2, range(10)))  
[1, 3, 5, 7, 9]
# 4을 2로 나눈 나머지는 0, 0은 '거짓'이니까 버려짐.
##################################################
>>> test = 'A, B, C, D'
>>> result = test.split(',')
>>> result
['A', ' B', ' C', ' D']
##################################################
>>> test = 'A, B, C, D'
>>> result = list(map(lambda x : x.strip(), test.split(',')))
>>> result
['A', 'B', 'C', 'D']

< 특정문자열 포함 파일찾기 >

더보기
grep -r [문자열] [찾으려는위치]
# ex) grep -r 112 ./*

< plt.plot 폰트 >

더보기
import matplotlib.pyplot as plt 
plt.figure(figsize=(16, 5))    # figure가로세로크기
plt.rc('font', size=20)        # 기본 폰트 크기
plt.rc('axes', labelsize=20)   # x,y축 label 폰트 크기
plt.rc('xtick', labelsize=50)  # x축 눈금 폰트 크기 
plt.rc('ytick', labelsize=20)  # y축 눈금 폰트 크기
plt.rc('legend', fontsize=20)  # 범례 폰트 크기
plt.rc('figure', titlesize=50) # figure title 폰트 크기

plt.rcParams['legend.fontsize'] = 16
plt.rcParams['figure.titlesize'] = 18
plt.rcParams['axes.titlesize'] = 18
plt.rcParams['lines.linewidth'] = 2.0
plt.rcParams['axes.labelsize'] = 18
plt.rcParams['xtick.labelsize'] = 16
plt.rcParams['ytick.labelsize'] = 16

< ipynb -> py >

더보기
# 확장자가 ipynb인 Jupyter Notebook 파일을 아래 명령어를 이용하여 python 파일로 변환. 아래 명령은 xgboost-wine-quality.ipynb 파일을 step0-xgboost-wine-quality.py 로 변환하는 예시.
jupyter nbconvert xgboost-wine-quality.ipynb --to script --output step0-xgboost-wine-qual

< 행추가 > 

더보기
latency_all.loc['best_gpu'] =  [0 for i in range(len(latency_all.columns))]

<>

+++

<특정문자가 문자열안에 포함되어있는지>

더보기
    check_models = ['MNIST_CNN','AlexNet','CIFAR10','InceptionV3',
                     'VGG19','ResNet50','InceptionResNetV2','LeNet5',
                   'ResNetSmall']
    for i in (check_models):
        if i in save_name:
            model = i

 

반응형

댓글()