pandas columns (rename, type, order, drop)

Published by onesixx on

컬럼 이름변경

import plotly.express as px
iris = px.data.iris()
iris.head(3)
#    sepal_length  sepal_width  petal_length  petal_width species  species_id
# 0           5.1          3.5           1.4          0.2  setosa           1
# 1           4.9          3.0           1.4          0.2  setosa           1
# 2           4.7          3.2           1.3          0.2  setosa           1


iris = iris.rename(columns={'sepal_length': 'sepa_l', 'sepal_width': 'sepal_w'})
#      sepa_l  sepal_w  petal_length  petal_width    species  species_id
# 0       5.1      3.5           1.4          0.2     setosa           1
# 1       4.9      3.0           1.4          0.2     setosa           1
# 2       4.7      3.2           1.3          0.2     setosa           1

칼럼 순서변경

import plotly.express as px
iris = px.data.iris()
iris.head(3)
#    sepal_length  sepal_width  petal_length  petal_width species  species_id
# 0           5.1          3.5           1.4          0.2  setosa           1
# 1           4.9          3.0           1.4          0.2  setosa           1
# 2           4.7          3.2           1.3          0.2  setosa           1

col_nm = sorted(list(iris.columns))
iris = iris[col_nm]
#    petal_length  petal_width  sepal_length  sepal_width species  species_id
# 0           1.4          0.2           5.1          3.5  setosa           1
# 1           1.4          0.2           4.9          3.0  setosa           1
# 2           1.3          0.2           4.7          3.2  setosa           1

컬럼 신규추가

iris['name'] = 'sixx'

iris.loc[:, 'name'] = 'sixx'

iris['grade'] = np.where(iris['sepal_length']>6, 'big', 'small')

iris['length_mean'] = (iris['sepal_length']+iris['petal_length'] )/2

컬럼 타입변경

iris.dtypes
iris = iris.astype({'species':'category'})
iris = iris.astype({'species_id':'object'})

iris['petal_length'] = iris['petal_length'].astype('int')

컬럼 삭제 : drop del pop

### drop  (row & column) 
iris = iris.drop('species', axis=1)
iris.drop('species', axis=1, inplace=True)
iris.drop(iris.index[[0,2]])

### del
del iris["species"]


### pop  (지운컬럼을 결과로 보여줌)
iris.pop('species')

Categories: pandas

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x