(pandas)intとstrが混在したDataFrameのstrが含まれる行だけを消したい!
English ver. is here
senior-badchallenge.hatenablog.com
こんにちは!今日もpythonの勉強をしていますか?
自分は最近、matplotlibとseabornの使い方の勉強をしています。
ここでめっちゃ大事になってくるのが「前処理」
やりたいことはあるんだけど、この前処理がなかなか大変。
前処理といえばpandasですよね!
(というか、これしか知らない・・・)
今回は、intとstrが混在したDataFrameがあって、
このうち、strが含まれる行だけを
マルっと消したい!ということを想定します。
自分はこんな感じで作ってみました!
##### ライブラリのインポート ##### import pandas as pd ##### 対象とするファイルの読み込み ##### data = pd.read_excel('data.xlsx') ##### strが入っているかチェックしたいcolumnをここで指定 ##### # リストで入力していきます。複数あってもOK。 # 例えばこんな感じ↓ str_check_columns = [column1, column2] ##### strが含まれている行をチェックして、削除する関数 ##### def delete_row_include_str(data, column): judge_data = data[column].to_list() row_num = 0 place_of_str = [] for judge in judge_data: if type(judge) is str: place_of_str.append(row_num) row_num += 1 data = data.drop(data.index[place_of_str]) return data ##### このfor文がstrが含まれている行を削除します ##### for str_check_column in str_check_columns: data = delete_row_include_str(data, str_check_column)