일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- Excel
- 맛집
- MySQL
- IOS
- flutter
- 유니티
- mssql
- PER
- Unity
- MS-SQL
- tensorflow
- javascript
- Linux
- 함수
- python
- pandas
- swift
- urllib
- PyQt5
- node.js
- GIT
- port
- PyQt
- ubuntu
- ASP
- 라즈베리파이
- sqlite
- 날짜
- 다이어트
- 리눅스
목록2025/07 (12)
아미(아름다운미소)
def process_dataframe_optimized(dict_df_types, df): type_handlers = { 'int': lambda s: pd.to_numeric(s, errors='coerce').fillna(0).astype('int32'), 'float': lambda s: pd.to_numeric(s, errors='coerce').fillna(0).astype('float32'), 'bool': lambda s: s.astype(str).str.lower().isin(['true', 't', '1']), 'datetime': lambda s: pd.to_datetime(s, errors='coerce'), 's..
cd ~/StudioProjects/stock-flutterflutter cleanflutter pub getcd android./gradlew --stop./gradlew cleancd ..flutter run -d emulator-5554
df1 = df.groupby(by=['a'], as_index=False).max() # 또는 다른 집계 함수df['a'] = np.nan if df1['a'].isnull().any() else df1['a'].max()# 컬럼 'a'가 있고, NaN이 아닌 값이 하나라도 있으면 최대값, 아니면 np.nandf['a'] = df1['a'].max() if 'a' in df1.columns and df1['a'].notna().any() else np.nan🎯 EX)import pandas as pdimport numpy as np# 예제 1: 'a' 컬럼이 있고, NaN이 아닌 값이 존재하는 경우df1 = pd.DataFrame({'a': [3, 7, np.nan]})df = pd.DataFram..
시작# ❌ 잘못된 원래 코드 (에러 발생)df['a'] = df1['a'].agg(lambda x: np.nan if x.isnull.any() else x.max()).reset_index(drop=True)# "전체에 null이 하나라도 있으면 np.nan, 아니면 최대값"# ✅ 올바르고 간결한 코드df['a'] = np.nan if df1['a'].isnull().any() else df1['a'].max()# 결론: 맞습니다! 이게 가장 pandas다운 깔끔한 코드입니다.# 복잡한 agg() 체이닝 대신 조건부 표현식 + 자동 브로드캐스팅을 활용한 완벽한 해결책🎯 결론 : 최종선택if 'a' in df1.columns: # NaN이 아닌 값이 하나라도 있으면 최대값, 아니면 np.nan ..
df['a'] = df1['a'].agg(lambda x: np.nan if x.isnull.any() else x.max()).reset_index(drop=True)Colums must be same length as key 에러원래 코드 `df['a'] = df1['a'].agg(...)`에서 발생한 에러는 `agg()`가 단일 값을 반환하기 때문에 `df['a']`의 길이와 맞지 않아서 발생한 문제수정import pandas as pdimport numpy as np# 1. 예제 데이터 생성df = pd.DataFrame({'other_col': [10, 20, 30]}) # 타겟 DataFrame (3행)df1 = pd.DataFrame({'a': [1, np.nan, 3]}) # 소..
import pandas as pddef add_blank_category_or_fillna(series): try: if pd.api.types.is_categorical_dtype(series): # ''가 이미 포함되어 있는지 확인 if '' not in series.cat.categories: return series.cat.add_categories(['']) else: return series else: return series.fillna('') except Exception as e: print(f"예외 발생: ..
import duckdb# DuckDB DB 파일에 연결 (없으면 생성됨)con = duckdb.connect("mydata.duckdb")# CSV 파일 읽어서 테이블로 저장con.execute("""CREATE TABLE my_table ASSELECT * FROM read_csv_auto('sample.csv')""")import pandas as pdimport duckdbdf = pd.read_csv("sample.csv")# DuckDB에 저장con = duckdb.connect("mydata.duckdb")con.register("df_view", df)# DataFrame을 테이블로 저장con.execute("CREATE TABLE my_table AS SELECT * FROM df_vie..
import tracebacktry: # 에러 유발 코드 (예시: 0으로 나누기) x = 1 / 0except Exception as e: print("❗ 에러 발생:", str(e)) traceback.print_exc() # 전체 에러 트레이스 출력import numpy as np# 인덱스가 다른 위치 찾기diff_indices = np.where(df.index != df1.index)[0]# 결과 출력print("인덱스가 다른 위치:", diff_indices)print("\n--- df의 인덱스 ---")print(df.index[diff_indices])print("\n--- df1의 인덱스 ---")print(df1.index[diff_indices])
first_date = df.get('날짜열', pd.Series([pd.NaT])).iloc[0]
import pandas as pd# 예시: 둘 다 빈 DataFrame이지만 컬럼이 다름df1 = pd.DataFrame(columns=['a', 'b'])df2 = pd.DataFrame(columns=['b', 'c'])# 👉 모든 컬럼의 합집합 구하기all_columns = sorted(set(df1.columns).union(set(df2.columns)))# 👉 컬럼 맞춰주기 (reindex로 없으면 NaN 채움)df1 = df1.reindex(columns=all_columns)df2 = df2.reindex(columns=all_columns)# 👉 concatresult = pd.concat([df1, df2], ignore_index=True)print(result)