![](/img/trans.png)
[英]How to find information between two words excluding white spaces using python re?
[英]how to find rows with white spaces in a dataframe, using python?
我有以下 dataframe。
import pandas as pd
import numpy as np
#Create a DataFrame
df1 = {
'State':[' Arizona AZ ',' Georgia GG ', ' Newyork NY','Indiana IN ','Florida FL '],
'Score1':[62,47,55,74,31],
'Score2':[332,'',35,73,61]}
df1 = pd.DataFrame(df1,columns=['State','Score1','Score2'])
print(df1)
它返回
State Score1 Score2
0 Arizona AZ 62 62
1 Georgia GG 47
2 Newyork NY 55 35
3 Indiana IN 74 73
4 Florida FL 31 61
現在,如果我對 Score1 和 Score2 都有值,我想添加另一列來判斷“通過”,當一個為空白時判斷“失敗”。
我認為波紋管做的工作,但沒有。
df1['pass/fail'] = np.where((df1['Score1'].isspace()) | (df1['Score2'].isspace()) , 'fail',' ')
如何添加一列以查看我是否有兩列的數據?
編輯:我的數據集實際上看起來像這樣
import pandas as pd
import numpy as np
#Create a DataFrame
df1 = {
'State':[' Arizona AZ ',' Georgia GG ', ' Newyork NY','Indiana IN ','Florida FL '],
'Score1':[62,47,55,nan,31],
'Score2':[332,'',35,73,61]}
df1 = pd.DataFrame(df1,columns=['State','Score1','Score2'])
print(df1)
'nan' 和 ' ' 都必須返回失敗。
通過astype(str)
將它們轉換為字符串,然后使用.str.fullmatch
和正則表達式\s*
檢查條目是否為空(空格)或充滿空格,例如''
或' '
等:
df1['pass/fail'] = np.where(
(df1['Score1'].astype(str).str.fullmatch(r"\s*") |
df1['Score2'].astype(str).str.fullmatch(r"\s*")),
'fail',
'pass')
要得到
State Score1 Score2 pass/fail
0 Arizona AZ 62 332 pass
1 Georgia GG 47 fail
2 Newyork NY 55 35 pass
3 Indiana IN 74 73 pass
4 Florida FL 31 61 pass
如果你想避免在那里重復,你可以將掩碼包裝在 function 中:
def is_blank_mask(df, column):
return df[column].astype(str).str.fullmatch(r"\s*")
接着
df1['pass/fail'] = np.where(is_blank_mask(df1, 'Score1') | is_blank_mask(df1, 'Score2'),
'fail',
'pass')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.