アラフォーおじさんの日常奮闘記

最近は多忙でバドミントンがご無沙汰になってきて、どちらかと言うと英語やプログラミング学習での気付きをシェアすることが多くなってきたブログ。

(pandas preprocessing)How to delete only rows that include str in DataFrame

(Japanese ver. is here.)
senior-badchallenge.hatenablog.com





Hi!

I'll share with you how to delete only rows that include str in DataFrame.




(expect situation)

Int and str exist mixedly in DataFrame.

We want to delete only rows that include str.



##### Import #####
import pandas as pd




##### Read data #####
data = pd.read_excel('data.xlsx')




##### Select columns for check including str #####
# e.g. (Below list includes selected column names)
str_check_columns = [column1, column2]




##### Function for delete 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




##### Execute the above function #####
for str_check_column in str_check_columns:
    data = delete_row_include_str(data, str_check_column)