[英]How to delete rows in a CSV file based on blank columns
我有一個這種格式的 csv 文件,但有數千行,所以我可以這樣總結
id,name,score1,score2,score3
1,,3.0,4.5,2.0
2,,,,
3,,4.5,3.2,4.1
我曾嘗試使用.dropna() 但這不起作用。
我想要的 output 是
id,name,score1,score2,score3
1,,3.0,4.5,2.0
3,,4.5,3.2,4.1
我真正需要的是檢查 score1 是否為空,因為如果 score1 為空,那么分數的 rest 也為空。
我也試過這個,但它似乎沒有做任何事情。
import pandas as pd
df = pd.read_csv('dataset.csv')
df.drop(df.index[(df["score1] == '')], axis=0,inplace=True)
df.to_csv('new.csv')
有人能幫忙嗎?
import pandas as pd
df = pd.DataFrame([[1,3.0,4.5,2.0],[2],[3,4.5,3.2,4.1]], columns=["id","score1","score2","score3"])
aux1 = df.dropna()
aux2 = df.dropna(axis='columns')
aux3 = df.dropna(axis='rows')
print('=== original ===')
print(df)
print()
print('=== mode 1 ===')
print(aux1)
print()
print('=== mode 2 ===')
print(aux2)
print()
print('=== mode 3 ===')
print(aux3)
print()
print('=== mode 4 ===')
print('drop original')
df.dropna(axis=1,inplace=True)
print(df)
看到您的編輯后,我意識到dropna
對您不起作用,因為您在所有行中都有一個None
值。 要過濾特定列中的nan
值,我建議使用apply
function,如下面的代碼所示。 (順便說一句, StackOverflow.csv
只是我從問題中復制並粘貼您的數據的文件)
import pandas as pd
import math
df = pd.read_csv("StackOverflow.csv", index_col="id")
#Function that takes a number and returns if its nan or not
def not_nan(number):
return not math.isnan(number)
#Filtering the dataframe with the function
df = df[df["score1"].apply(not_nan)]
這樣做是遍歷score1
行並檢查值是否為NaN
。 如果是,則返回 False。 然后,我們使用True
和False
值列表從 dataframe 中過濾掉值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.