반응형
DataFrame columns 작업
열 인덱스 및 레이블 가져오기
idx = df.columns
label = df.columns[0] # 첫번째 컬럼
l = df.columns.tolist()
a = df.columns.values
열 레이블 변경
df = df.rename(columns={'old':'new','a':'1'})
df.columns = ['new1', 'new2', 'new3']
열 선택
s = df['colName'] # select col to Series
df = df[['colName']] # select col to df
df = df[['a','b']] # select 2-plus cols
df = df[['c','a','b']] # change col order
s = df[df.columns[0]] # select by number
df = df[df.columns[[0, 3, 4]]] # by numbers
df = [df.columns[:-1]] # all but last col
s = df.pop('c') # get & drop from df
Python 속성이 있는 열 선택
s = df.a # same as s = df['a']
# cannot create new columns by attribute
df.existing_column = df.a / df.b
df['new_column'] = df.a / df.b
DataFrame에 새 열 추가
df['new_col'] = range(len(df))
df['new_col'] = np.repeat(np.nan,len(df))
df['random'] = np.random.rand(len(df))
df['index_as_col'] = df.index
df1[['b','c']] = df2[['e','f']]
df3 = df1.append(other=df2)
열 내용 교환
df[['B', 'A']] = df[['A', 'B']]
열 삭제 (주로 레이블 기준)
df = df.drop('col1', axis=1)
df.drop('col1', axis=1, inplace=True)
df = df.drop(['col1','col2'], axis=1)
s = df.pop('col') # drops from frame
del df['col'] # even classic python works
df = df.drop(df.columns[0], axis=1)#first
df = df.drop(df.columns[-1:],axis=1)#last
열의 벡터화된 산술
df['proportion']=df['count']/df['total']
df['percent'] = df['proportion'] * 100.0
열에 numpy 수학 함수 적용
df['log_data'] = np.log(df['col1'])
기준에 따라 설정된 열 값 설정
df['b'] = df['a'].where(df['a']>0, other=0)
df['d'] = df['a'].where(df.b!=0, other=df.c)
데이터 유형 변환
st = df['col'].astype(str)# Series dtype
a = df['col'].values # numpy array
l = df['col'].tolist() # python list
일반적인 열 전체 메서드/속성
value = df['col'].dtype # type of data
value = df['col'].size # col dimensions
value = df['col'].count() # non-NA count
value = df['col'].sum()
value = df['col'].prod()
value = df['col'].min()
value = df['col'].max()
value = df['col'].mean() # also median()
value = df['col'].cov(df['col2'])
s = df['col'].describe()
s = df['col'].value_counts()
열의 최소/최대 값에 대한 인덱스 레이블 찾기
label = df['col1'].idxmin()
label = df['col1'].idxmax()
일반적인 열 요소별 방법
s = df['col'].isnull()
s = df['col'].notnull() # not isnull()
s = df['col'].astype(float)
s = df['col'].abs()
s = df['col'].round(decimals=0)
s = df['col'].diff(periods=1)
s = df['col'].shift(periods=1)
s = df['col'].to_datetime()
s = df['col'].fillna(0) # replace NaN w 0
s = df['col'].cumsum()
s = df['col'].cumprod()
s = df['col'].pct_change(periods=4)
s = df['col'].rolling(window=4,
min_periods=4, center=False).sum()
DataFrame에 행 합계 열 추가
df['Total'] = df.sum(axis=1)
DataFrame의 모든 열을 시리즈별로 곱하기
df = df.mul(s, axis=0) # on matched rows
.loc, .iloc 및 .ix를 사용하여 열 선택
df = df.loc[:, 'col1':'col2'] # inclusive
df = df.iloc[:, 0:2] # exclusive
열 인덱스 레이블의 정수 위치 가져오기
i = df.columns.get_loc('col_name')
열 인덱스 값이 고유하거나 단조로운지 확인하기
if df.columns.is_unique: pass # ...
b = df.columns.is_monotonic_increasing
b = df.columns.is_monotonic_decreasing
참고 : https://www.geeksforgeeks.org/pandas-cheat-sheet
Pandas Cheat Sheet for Data Science in Python
This cheat sheet provides a quick reference to the most common Pandas commands, covering everything from data loading and manipulation to plotting and visualization. Whether you're a beginner or a seasoned data scientist, this cheat sheet is a valuable res
www.geeksforgeeks.org
반응형
'Python' 카테고리의 다른 글
python 판다스(pandas) DataFrame 셀 cells 작업 (2) | 2023.11.12 |
---|---|
python 판다스(pandas) DataFrame rows 행 작업 (0) | 2023.11.12 |
python 판다스(pandas) DataFrame 구조 통계 확인하기 (0) | 2023.10.21 |
python 판다스(pandas) DataFrame 만들기 CSV 가져오기 (2) | 2023.10.21 |
Rosalind - Consensus and Profile (2) | 2023.10.15 |