pandas & duckdb
-
DuckDB 에서 PostgreSQL 연결하기pandas & duckdb 2025. 10. 31. 22:20
import duckdb# (1) DuckDB 연결 — 메모리 또는 파일 DBcon = duckdb.connect() # 메모리 기반# 또는# con = duckdb.connect("mydb.duckdb") # 파일 기반# (2) PostgreSQL extension 설치 / 로드 (필요한 경우)con.execute("INSTALL postgres;")con.execute("LOAD postgres;")# (3) PostgreSQL DB를 ATTACH# 예: 로컬의 PostgreSQL 인스턴스, 기본 스키마 publiccon.execute("""ATTACH 'dbname=postgres user=postgres host=127.0.0.1 port=5432 password=mypassword' AS ..
-
DuckDB 에서 pyspark api 사용하기pandas & duckdb 2025. 10. 31. 22:18
https://duckdb.org/docs/stable/clients/python/spark_apifrom duckdb.experimental.spark.sql import SparkSession as sessionfrom duckdb.experimental.spark.sql.functions import lit, colimport pandas as pdspark = session.builder.getOrCreate()pandas_df = pd.DataFrame({ 'age': [10, 20, 30]})df = spark.createDataFrame(pandas_df)res = df.select(col('age'))res.toPandas().head()
-
자주 쓰는 Pandas 코드pandas & duckdb 2024. 8. 13. 11:08
데이터 통계 보기df.info()df.describe()df.describe(include='object') df.value_counts() 데이터 필터링df[['name', 'age']]df.loc[df['a'] > 10, ['a', 'c']] # Select rows meeting loglogical condition, and only the specific columns .df.sample(frac=0.5)df.sample(n=10) # Randomly select n rows. 1개의 Cell 읽어 DataFrame 이 아닌 원래 type 으로 리턴하기web_doc_meta.loc[web_doc_meta['key'] == 'vTime', 'value'].to_numpy()[0] Colum..
-
Time Series 데이터를 시각화pandas & duckdb 2022. 10. 25. 21:28
문제 1초 단위로 저장된 2분간의 데이터(0~500 사이의 값) 를 10초 단위로 나누어 평균값을 시각화 한다. 코드 import pandas as pd import numpy as np import plotly.express as px rng = pd.date_range("1/1/2012", periods=120, freq="S") # freq="S" 초 단위로 ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng) df = ts.resample('10S').aggregate(np.average) # 10초 단위로 grouping 후 평균을 구함 fig = px.line(df) fig.show() 결과
-
데이터 전처리, 추가, 삭제, 변환pandas & duckdb 2022. 10. 8. 21:39
import pandas as pd import seaborn as sns df = sns.load_dataset('titanic') # 임의의 값을 대입하여 새로운 컬럼을 마지막에 추가 df['VIP'] = True # 중간에 컬럼을 추가하고 싶은 경우 insert()를 활용 df.insert(5, 'RICH', df['fare'] > 100) # 행 삭제 df.drop(1) df.drop([1, 3, 5]) df.drop(range(1, 10)) # 열 삭제 df.drop('class', axis=1) df.drop(['who', 'deck'], axis=1) # 삭제된 내용을 바로 적용하려면 inplace=True를 지정 df.drop(['who', 'deck'], axis=1, inplace=Tr..
-
복사와 결측치pandas & duckdb 2022. 10. 8. 20:23
import seaborn as sns df = sns.load_dataset('titanic') df_copy = df.copy() # 결측치 갯수를 확인하기 위해서는 sum() 활용 df.isnull().sum() df.notnull().sum() # 결측치 필터링 df.loc[df['age'].isnull()] # 결측치 채우기 df['age'].fillna(50) # 결측치를 평균으로 채우기 df['age'].fillna(df['age'].mean()) # 결측치를 최빈값으로 채우기 # 최빈값(mode)으로 채울 때에는 반드시 0번째 index 지정하여 값을 추출한 후 채워야 합니다. v = df['deck'].mode()[0] df['deck'].fillna(v) # 1개 라도 NaN 값이 있는..
-
통계pandas & duckdb 2022. 10. 8. 19:56
import seaborn as sns import pandas as pd df = sns.load_dataset('titanic') df.info() df.describe() df.count() df['age'].count() df.mean() df['age'].mean() cond = df['alive'] == 'yes' df[cond]['age'].mean() df.loc[cond, 'age'].mean() # skipna=True가 기본으로 설정 되어 있습니다. # skipna=False로 설정하게 된다면, NaN 값이 있는 column은 NaN 값으로 출력 됩니다. df.mean(skipna=False) pd.Series([4, 5, 1, 2, 3]).median() # 3.0 pd.Series..
-
조회, 정렬, 필터pandas & duckdb 2022. 8. 20. 23:33
import seaborn as sns df = sns.load_dataset("titanic") ############################################################ # 데이터 살펴보기 df[['pclass', 'age']] # 특정 column 만 보기 df.head() df.head(10) df.tail() df.tail(10) df.info() df.describe() df.describe(include='object') # 문자열에 대한 통계 df['who'].value_counts() ############################################################ # 속성 df.ndim df.shape df.index df.c..