랭귀지/pandas
특정열이 1보다큰경우 fillcount
유키공
2024. 8. 27. 08:45
import pandas as pd
import numpy as np
# 샘플 데이터 생성
data = {
'a': ['A'] * 6 + ['B'] * 6 + ['C'] * 6,
'b': [10, 15, 10, -20, 5, 10,
25, -30, 5, 20, 15, 10,
10, 15, 20, 25, 30, 35],
'c': [3, 3, 3, 3, 3, 3,
-3, -3, -3, -3, -3, -3,
2, 2, 2, 2, 2, 2]
}
# DataFrame 생성
df = pd.DataFrame(data)
# d 컬럼과 e 컬럼 초기화
df['d'] = np.nan
df['e'] = np.random.randint(-5, 10, size=len(df)) # e 컬럼에 랜덤 값 추가
# 각 그룹별로 d 컬럼 채우기
for name, group in df.groupby('a'):
if not group.empty: # 그룹이 비어있지 않은지 체크
count = group['c'].iloc[0] # 첫 번째 행의 c 값을 가져옴
# e 컬럼이 0보다 큰 행에 대한 boolean 인덱스 생성
positive_e_rows = group['e'] > 0
if count > 0:
fill_count = min(count, positive_e_rows.sum()) # c 값과 양수 e 행의 개수 중 작은 값
df.loc[group[positive_e_rows].index[:fill_count], 'd'] = 1 # c가 양수일 경우 1로 채움
elif count < 0:
fill_count = min(abs(count), positive_e_rows.sum()) # 절대값과 양수 e 행의 개수 중 작은 값
df.loc[group[positive_e_rows].index[:fill_count], 'd'] = -1 # c가 음수일 경우 -1로 채움
# 결과 출력
print(df[['a', 'b', 'c', 'd', 'e']])
import pandas as pd
import numpy as np
# 샘플 데이터 생성
data = {
'a': ['A'] * 6 + ['B'] * 6 + ['C'] * 6,
'b': [10, 15, 10, -20, 5, 10,
25, -30, 5, 20, 15, 10,
10, 15, 20, 25, 30, 35],
'c': [3, 3, 3, 3, 3, 3,
-3, -3, -3, -3, -3, -3,
2, 2, 2, 2, 2, 2]
}
# DataFrame 생성
df = pd.DataFrame(data)
# d 컬럼과 e 컬럼 초기화
df['d'] = np.nan
df['e'] = np.random.randint(-5, 10, size=len(df)) # e 컬럼에 랜덤 값 추가
# 각 그룹별로 d 컬럼 채우기
for name, group in df.groupby('a'):
if not group.empty: # 그룹이 비어있지 않은지 체크
count = group['c'].iloc[0] # 첫 번째 행의 c 값을 가져옴
# e 컬럼이 0보다 큰 행만 처리
positive_e_rows = group[group['e'] > 0]
if count > 0:
fill_count = min(count, len(positive_e_rows)) # c 값과 양수 e 행의 길이 중 작은 값
df.loc[positive_e_rows.index[:fill_count], 'd'] = 1 # c가 양수일 경우 1로 채움
elif count < 0:
fill_count = min(abs(count), len(positive_e_rows)) # 절대값과 양수 e 행의 길이 중 작은 값
df.loc[positive_e_rows.index[:fill_count], 'd'] = -1 # c가 음수일 경우 -1로 채움
# 결과 출력
print(df[['a', 'b', 'c', 'd', 'e']])