Notice
Recent Posts
Recent Comments
Link
아미(아름다운미소)
pandas 컬럼값변경 본문
import pandas as pd
# df1 생성
df1 = pd.DataFrame({
'a': [1, 2, 3, 1, 2, 3, 4],
'b': [10, 20, 30, 40, 50, 60, 70],
'c': [100, 200, 300, 400, 500, 600, 700],
'd': [1000, 2000, 3000, 4000, 5000, 6000, 7000]
})
# 수정된 df2 생성 (a-1을 키로 사용)
df2 = pd.DataFrame({
'a-1': [1, 2, 3],
'b': [15, 25, 35] # 각 a에 해당하는 b 값
})
# Left Outer Join 수행 (a와 a-1을 키로 사용)
left_outer_join_df = pd.merge(df1, df2, left_on='a', right_on='a-1', how='left', suffixes=('', '_left'))
# print(left_outer_join_df)
# b 컬럼 업데이트
# left_outer_join_df['b'] = left_outer_join_df['b_left'].combine_first(left_outer_join_df['b'])
left_outer_join_df['b'] = left_outer_join_df['b_left'].fillna(left_outer_join_df['b'])
# print(left_outer_join_df)
# 불필요한 b_new 및 a-1 컬럼 제거
left_outer_join_df = left_outer_join_df.drop(columns=['b_left', 'a-1'])
# 결과 출력
print(left_outer_join_df)
a b c d
0 1 15.0 100 1000
1 2 25.0 200 2000
2 3 35.0 300 3000
3 1 15.0 400 4000
4 2 25.0 500 5000
5 3 35.0 600 6000
6 4 70.0 700 7000
'랭귀지 > pandas' 카테고리의 다른 글
pandas 전주차 구하기 (0) | 2024.07.23 |
---|---|
pandas 컬럼이름을 마지막으로이동 (0) | 2024.07.22 |
pandas 참조 df 특정 컬럼값으로 값채우기 (0) | 2024.07.19 |
pandas dataframe 컬럼비교 (0) | 2024.07.18 |
pandas filter (0) | 2024.07.17 |
Comments