Python 2022. 5. 30. 11:38

dataframe column의 index를 가져오는 코드

import pandas as pd

df = pd.read_csv("")

df.columns.get_loc("columns_name")
posted by 초코렛과자
:
Python 2022. 5. 29. 16:53

일자별로 이미지 파일을 분류 할 일이 생겨서 만들게 되었다.

PIL 라이브러리를 이용해서 상세정보에서 사진이 찍힌날짜를 가져오는 방식으로 분류.

 

# -*- coding: utf-8 -*-
"""
1. 파일 경로를 잡는다.
2. 해당 경로 내 모든 사진파일 확장자를 가진 파일을 읽는다.
3. 해당 파일들의 속성에서 일자를 가져온다.
4. 가져온 일자들의 유니크 값을 생성해서, 해당 값들로 폴더를 생성한다.
5. 생성한 폴더에 각 일자의 사진들을 옮긴다.
6. 옮길 때, 동일한 파일이 있을 경우 continue
"""
"""
    함수화는 나중에 일단 구현
"""
import os
import shutil
from datetime import datetime
from PIL import Image
from PIL.ExifTags import TAGS

target_folder = './data/'
img_folder = './img_result/'
video_folder = './video_result/'

folder_list = os.listdir(target_folder)

# set(map(lambda x: x.split('.')[1],file_list))
# 가지고 와야하는 이미지 파일이 JPG만 있음
# 영상은 MOV,MP4

def split_files(file_folder,file_list,type_folder,target_type):
    file_dict = {}
    for f in file_list:
        if target_type == 'image':
            image = Image.open(file_folder+f)
            exifdata = image.getexif()
            
            for tag_id in exifdata:
                tag = TAGS.get(tag_id,tag_id)
                data = exifdata.get(tag_id)
                if tag  == 'DateTime':  
                    break
            if tag == 'DateTime':
                file_date = datetime.strptime(data.split(" ")[0],"%Y:%m:%d")
            else:            
                file_stat = os.stat(file_folder+f)
                file_date = datetime.fromtimestamp(file_stat.st_mtime)
        else:
            file_stat = os.stat(file_folder+f)
            file_date = datetime.fromtimestamp(file_stat.st_mtime)
        month = file_date.month
        day = file_date.day
        date = ''
        if month < 10:
            if day < 10:
                date = '0'+str(month) +'0'+ str(day)
            else:
                date = '0'+str(month) + str(day)
        else:
            if day < 10:
                date = str(month) +'0'+ str(day)
            else:
                date = str(month) + str(day)
        file_dict[f] = date
    
    for mkfolder in set(list(file_dict.values())):
        if not os.path.isdir(type_folder+mkfolder):
            os.mkdir(type_folder+mkfolder)
            
    for file_name, file_date in file_dict.items():
        if os.path.isfile(os.path.join(type_folder,file_date,file_name)):
            # new_file_name = file_name.split('.')[0]+str(datetime.now().microsecond)+'.'+file_name.split('.')[1]
            # os.rename(file_folder+file_name,file_folder+new_file_name)
            # shutil.copy2(file_folder+new_file_name, type_folder+file_date)
            continue
        else:
            shutil.copy2(file_folder+file_name, type_folder+file_date)
    
for folder in folder_list:
    img_list = []
    video_list = []
    file_folder = target_folder+folder+'/'
    file_list = os.listdir(file_folder)
    for f in file_list:
        if f.split('.')[1] == 'JPG':
            img_list.append(f)
        elif f.split('.')[1] == 'MOV' or f.split('.')[1] == 'MP4':
            video_list.append(f)
    split_files(file_folder,img_list,img_folder,'image')
    split_files(file_folder,video_list,video_folder,'video')
posted by 초코렛과자
:
Python 2022. 5. 2. 11:05
def percentile(n):
    def percentile_(x):
        return np.percentile(x, n)
    percentile_.__name__ = 'percentile_%s' % n
    return percentile_
    
column.agg([np.sum, np.mean, np.std, np.median,
                     np.var, np.min, np.max, percentile(50), percentile(95)])
posted by 초코렛과자
:
Python 2022. 3. 30. 07:46

python 에서 float 값을 그냥 계산하면 아래와 같이 값이 이상하게(?) 나오는 경우가 있다

 

이럴 경우 decimal 이라는 라이브러리를 이용하면 부동소수점 계산이 제대로 되는데 예제는 다음과 같다

from decimal import Decimal
x = Decimal('0.3')
y = Decimal('0.1')
float(x-y)

이렇게 하면 값이 0.2 가 나오는게 확인

posted by 초코렛과자
:
Python 2022. 3. 17. 12:44
pivot_table.reset_index().rename_axis(None, axis=1)

'Python' 카테고리의 다른 글

dataframe groupby agg percentile  (0) 2022.05.02
decimal. 부동소수점 계산을 위한 라이브러리  (0) 2022.03.30
jupyter에서 warning 메시지 제거  (0) 2022.01.10
기간별 주차 만들기  (0) 2021.12.07
dataframe isin 함수  (0) 2021.06.24
posted by 초코렛과자
:
Python 2022. 1. 10. 10:29
import warnings
warnings.filterwarnings(action='ignore') #경고 무시

 

posted by 초코렛과자
:
Python 2021. 12. 7. 22:10
start = '2021-07-28 06:00:00'
end = '2021-08-04 06:00:00.000'
for i in range(33):
    temp_idx = df[(df['Time'] >= start) & (df['Time'] <= end)].index
    df.loc[temp_idx,'week'] = i        
    start = str(pd.to_datetime(start)+pd.Timedelta(7, unit='D'))
    end = str(pd.to_datetime(end)+pd.Timedelta(7, unit='D'))
posted by 초코렛과자
:
Python 2021. 6. 24. 10:28
temp_list = [1,2,3]
df[df['대상column'].isin(temp_list)]

dataframe isin 함수 이용해서 

posted by 초코렛과자
:
Python 2021. 6. 18. 13:01
df = pd.read_csv('FILENAME',
        header=0,
        usecols=["Time", "Name"])

usecols parameter 사용

posted by 초코렛과자
:
Python 2021. 6. 7. 11:52
df2 = df[~df.Name.str.contains('단어')]

 

'Python' 카테고리의 다른 글

dataframe isin 함수  (0) 2021.06.24
Dataframe read csv 원하는 column만 가져오기  (0) 2021.06.18
dataframe 범위별 구간 만들기  (0) 2021.06.02
pandas read csv시 thousand 숫자형으로 읽기  (0) 2021.05.24
plotly를 이용한 pca  (0) 2021.05.18
posted by 초코렛과자
: