sourcetip

팬더의 데이터 프레임에서 다른 데이터 프레임으로 행 복사

fileupload 2023. 9. 20. 20:40
반응형

팬더의 데이터 프레임에서 다른 데이터 프레임으로 행 복사

저는 파이썬, 팬더, 마리아드브를 처음 접했는데 당신의 도움과 조언이 필요합니다.저는 한 달의 매일 작업을 수행하는 데이터가 포함된 csv 파일을 가지고 있습니다.특정일의 값을 모두 추출하여 데이터베이스에 삽입해야 합니다.모든 데이터를 DataFrame에 저장하려고 생각했는데, 그 날의 데이터를 반복해서 다른 DataFrame에 저장하려고 생각했는데, 다음과 같은 경고가 나타납니다.

The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.

지금까지 제 코드는 다음과 같습니다.

import datetime as dt
import pandas as pd

data = pd.read_csv('./files/salesreport.csv',
                   names=['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6',
                          'col_7', 'col_8', 'col_9', 'col_10'],
                   sep=',',
                   header=None,
                   keep_default_na=False,
                   na_values="")


df = pd.DataFrame(data)
pd.set_option('display.max_columns', None)

now = dt.datetime.now()
# today_date = now.strftime("%m-%d-%Y")

today_date = '07-17-2022' //i'm using this date for testing
tmp_df = pd.DataFrame()

for (index, row) in df.iterrows():
    if row.col_1 == today_date:
        tmp_df = tmp_df.append(row, ignore_index=True) 

파일이 너무 크면 성능 문제도 발생할 수 있다고 생각합니다.데이터베이스에 특정일에 특정한 기록만 삽입할 수 있는 최적의 해결책을 찾을 수 있도록 도와주실 수 있나요?그리고 MariaDB로 데이터베이스에 삽입하는 가장 좋은 방법이 무엇인지 알려주시겠습니까?

감사합니다!

이것은 제게 간단한 필터로 간단한 필터처럼 들립니다.

tmp_df = df[df.col_1 == today_date]

(그리고 당신은 이것을 따를 수 있습니다..reset_index(), 그게 중요하다면)

실제로, 반복되는 맹장은 느리고 팬더와 함께 일하기에는 좋지 않은 모델입니다.

이렇게 될 수도 있습니다.

import pandas as pd
from sqlalchemy import create_engine

engine=create_engine('mysql+pymysql://root:root@localhost/test')

df= pd.read_csv('../files/salesreport.csv', names=['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6',
                          'col_7', 'col_8', 'col_9', 'col_10'], sep=',', header=None)
#filter by date
df = df[df['col_1'].str.contains('07-17-2022')]
#write data to mysql
df.to_sql('salesreport', engine, schema='test', if_exists='replace', index=True, index_label='id')

또는 날짜 시간으로 변환합니다.

#convert to datetime
df['col_1']=pd.to_datetime(df['col_1'], format='%m-%d-%Y')
#filter by date
df=df[df['col_1']=='2022-07-17']

언급URL : https://stackoverflow.com/questions/73362082/copy-rows-from-a-dataframe-to-another-dataframe-in-pandas

반응형