[英]How to find the value_count of a specific string in each column of the dataframe
我想找到字符串'\N'
出現在 dataframe df的每一列中的次數。
我試過這個:
for col in df.columns:
print(df[col].value_counts()['\N'])
並且系統返回錯誤,例如
unicode 錯誤 unicode 無法在 position 中解碼 0-1
你知道怎么解決嗎?
反斜杠 () 字符用於轉義具有特殊含義的字符,例如換行符、反斜杠本身或引號字符( 參見 python 詞法分析)
假設這個df:
a b
0 \N 1
1 \N 4
2 K \N
使用您的代碼將產生:
for col in df.columns:
print(df[col].value_counts()['\N'])
File "<ipython-input-83-64eb7c05f66f>", line 2
print(df[col].value_counts()['\N'])
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: malformed \N character escape
如果添加額外的反沖,您將獲得:
for col in df.columns:
print(f"{col} has",df[col].value_counts()['\\N']," \\N in it")
a has 2 \N in it
b has 1 \N in it
如果您使用df.to_dict()
,您也可以清楚地看到這一點:
>>> df.to_dict()
Out[901]: {'a': {0: '\\N', 1: '\\N', 2: 'K'}, 'b': {0: '1', 1: '4', 2: '\\N'}}
^ ^ ^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.