0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pandas 覚書き

Last updated at Posted at 2022-04-07

spreadsheetでは大きすぎるファイルをpandasで処理する際に必要な関数の覚書き

## インポート
import pandas as pd
df = pd.read_csv('filepath', sep=',')

## データの概要確認
print('dataframeの行数・列数の確認==>\n', df.shape)
print('indexの確認==>\n', df.index)
print('columnの確認==>\n', df.columns)
print('dataframeの各列のデータ型を確認==>\n', df.dtypes)
print('欠損値(NaN)の確認',df.isnull().sum())

## 前処理(Na)
df.fillna(value={'column_1': 0.0}, inplace=True)
df.dropna(subset=['column_1'], axis=0, inplace=True) 

## 前処理
df['column_1'] = df['column_1'].str.replace('--', 0).astype(float)
pd.DataFrame(df['column_1'].mask(df['column_1'] > 95, 100))
df.drop(['column_1'], axis=1, inplace=True) # column_1自体を削除

## 参照
df['ColumnName'] #=> series
df[['ColumnName1', 'ColumnName2']] #=> dataframe
df['IndexName'] #=> Series


## Filter
df[1:2] #=> dataframe, 行番号でのアクセスはスライスしかできない。df[1]はエラー
df.loc['IndexName'] #=> Series
df.loc[['IndexName1', 'IndexName2']] #=> Series
df.iloc[IndexNum] #=> Series
df[df.column1 == 'condition1'] #=> dataframe
df[df.column1.map(lambda x: x == 'condition1')] #=> dataframe

## Sort
df.sort_values(['column1'])

## 列挿入
series = pd.Series(['X2', 'X3', 'X4'], index=['TWO', 'THREE', 'FOUR'], name='X')
df['NewLabel'] = 0
df['NewLabel'] = series
df2 = df.assgin(X=func(df['A'])) #非破壊。XはそのままLabel名

## 結合
pd.merge(data_frame1, data_frame2, how="inner" ,on="id")

## group_by
df.groupby('key')
df.groupby('key').agg({
  'column1': 'sum',
  'column2': 'mean',
  'column3': 'count',
  'column4': lambda xs: ','.join([x for x in xs if x.strip()])
  'column5': lambda xs: xs.iloc[0]
})

## column名の変更
df = df.rename(columns={'old_column_name': 'new_column_name'})

## 集計
# weather列の集計
df['weather'].value_counts()

# groupbyメソッドで、'week'列ごとに'soldout'の数をカウントする
df.groupby(['week'])['soldout'].count()

# テキストデータが入っている列全てをdummy化(=one hotベクトル化)する
dummy_df = pd.get_dummies(df, columns=['week', 'name', 'event', 'weather', 'period'])
dummy_df.head()

よく使う処理

ある列でuniqな最初の行だけを取得

df = df[~df.duplicated(subset='column1')]

一つの列にある複数選択された値を列ごとにバラしてカウントする

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?