3
5

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 3 years have passed since last update.

[Python][Pandas] Dataframeの列の処理いろいろ

Last updated at Posted at 2021-03-22

個人的な備忘録です。

pandasの文字列の列にスライスを適用
https://note.nkmk.me/python-pandas-str-slice/
df['a'].str[:2]

pandasで文字の長さによる抽出
https://ja.stackoverflow.com/questions/63216/pandas%E3%81%A7%E6%96%87%E5%AD%97%E3%81%AE%E9%95%B7%E3%81%95%E3%81%AB%E3%82%88%E3%82%8B%E6%8A%BD%E5%87%BA
mask = df['moji'].str.len() >= 3
df[mask]

pandas.DataFrame, Seriesの要素の値を置換するreplace 正規表現
()で囲んだ部分をグループとして、置換後の値の中で\1, \2のように順番に使用可能。
https://note.nkmk.me/python-pandas-replace/
df.replace('(.)li(.)', r'\1LI\2', regex=True)
※rを入れるのを忘れないこと!

カラム名変更
df.rename(columns={'A': 'a', 'C': 'c'})
※意外に面倒・・

データフレームの列・行の合計追加
df['Total'] = df.sum(axis=1) #列
df.loc['Total']= df.sum() #行
https://stackoverflow.com/questions/20804673/appending-column-totals-to-a-pandas-dataframe

Change to datetime format 強引にdatetimeに変換
https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-separately-from-pandas-datetime-column
df['date_column'] = pd.to_datetime(df['date_column'])

DatetimeからYYYY-MMに変換する
df['Month']=df['Month'].dt.strftime('%Y-%m')

列の中で条件に合うものを、他の列の値にする
loc, ilocでブールインデックス参照
https://note.nkmk.me/python-pandas-where-mask/
df.loc[~(df['A'] < 0), 'A'] = df['B']

ちょっと複雑な例:
df.loc[(~df["dest"].str.contains('USA')) & (df['name']=='mellisa'), 'name'] = 'hole'

(列には関係ないが、便利なので載せておく)

全部のシートへアクセス
for sheetN in pd.ExcelFile(fname).sheet_names:
https://stackoverflow.com/questions/26521266/using-pandas-to-pd-read-excel-for-multiple-worksheets-of-the-same-workbook

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?