2017-09-18 7 views
0

私はCSVファイルの興味深いフィルタリングを行うためにパンダを使用してきましたが、ロードブロッキングに遭遇しました。インデックスの列に文字化けしたテキスト(非整数)データがないかチェックし、その行を削除しようとしています。私は条件を使用してインポート時にデータフレームからそれらを削除しようとしましたが、私は成功せずに後でそれらを反復しようとしました。ここに例があります:数字以外のインデックスを持つデータフレームから行を削除する

df = pd.read_csv(file, encoding='cp1252').set_index("numbers") 
results = df[df["columnA"].str.contains("search_data") & ~df["columnB"].isin(seach_list)] 
#I need to add to the above statement to check column "numbers" which I have set to be the index, 
#to catch some expected garbled text and filter it out... because it is 
#an integer, I can't use str.contains or isdigit or isalnum, I've tried to do len(df["columns"] < 20 , df.index < 20 .... i've tried 
#i've tried a few other options at this point as well 
# after bringing it in, I've also tried iterating through it: 
# 
for index, row in results.iterrows(): 
    if not (isinstance(row["numbers"], int)): 
     print(str(row["numbers"])) 
     #append whole row to new dataframe 
#This also didn't work 

私は何ができるでしょうか?サイドノートとして

Example data in the "numbers columns = 329381432 
Example garbled text in "numbers" column that I am 
trying to keep from importing: äu$ÒÔ”5$ò"Â$”äu$ÒÔ”5$ò 

、私はいくつかの非UTF-8データがあったとき、私はまだ、ファイル内のすべての良いデータを読み取ることができるように、PD機能のエンコーディングを変更しなければならなかった...それ以外の場合は、希望インポート時にエラーを投げます。

答えて

0

を使用して、numbers列を数値に変換することができます。すべての非数値項目は強制的にNaNになります。これらの行を削除することができます。

df = pd.read_csv(file, encoding='cp1252') 
df['numbers'] = pd.to_numeric(df['numbers'], errors='coerce') 

df = df.dropna(subset=['numbers']).set_index('numbers') 
関連する問題