Development/Python
[Python] Pandas DataFrame 원하는 순서에 컬럼 추가
성딱이
2022. 11. 25. 17:57
반응형
1. 소스코드
# 코드
df.insert(loc=추가위치, column='컬럼명', value= 시리즈 or 값 or 리스트 )
2. 예제 진행
# 예제 데이터
df = pd.DataFrame({'col_A':['a','b','c','d']
,'col_B':[0,1,2,3]})
df
Out[5]:
col_A | col_B | |
---|---|---|
0 | a | 0 |
1 | b | 1 |
2 | c | 2 |
3 | d | 3 |
In [4]:
# 예제1 : 첫 번째 위치에 pd.Series 데이터 삽입
add_series = pd.Series([2,3,4,5])
df.insert(loc=0, column='add_col', value=add_series)
df
Out[7]:
add_col | col_A | col_B | |
---|---|---|---|
0 | 2 | a | 0 |
1 | 3 | b | 1 |
2 | 4 | c | 2 |
3 | 5 | d | 3 |
In [8]:
# 예제 2 : 3번째 위치에 값(string) 데이터 삽입
df.insert(loc=2, column='add_col2', value='string')
df
Out[9]:
add_col | col_A | add_col2 | col_B | |
---|---|---|---|---|
0 | 2 | a | string | 0 |
1 | 3 | b | string | 1 |
2 | 4 | c | string | 2 |
3 | 5 | d | string | 3 |
In [10]:
# 예제 3 : 2번째 위치에 리스트 데이터 삽입
df.insert(loc=1, column='add_col3', value=[0,7,2,4])
df
Out[10]:
add_col | add_col3 | col_A | add_col2 | col_B | |
---|---|---|---|---|---|
0 | 2 | 0 | a | string | 0 |
1 | 3 | 7 | b | string | 1 |
2 | 4 | 2 | c | string | 2 |
3 | 5 | 4 | d | string | 3 |
끄-읏
반응형