如何根据基于行的表达式中的单元格内容过滤行

nic*_*omp 1 python python-3.x pandas

我从文件中读取了一些数据。由于第一个数据行中的 XXX,第一列被指定为“object”类型:

tips = pd.read_csv("tips.csv")
print(tips.head())
print(tips.info())

total_bill   tip     sex smoker  day    time  size    
0        xxx  1.01  Female     No  Sun  Dinner     2    
1      10.34  1.66    Male     No  Sun  Dinner     3    
2      21.01  3.50    Male     No  Sun  Dinner     3    
3      23.68  3.31    Male     No  Sun  Dinner     2    
4      24.59  3.61  Female     No  Sun  Dinner     4    
<class 'pandas.core.frame.DataFrame'>    
RangeIndex: 244 entries, 0 to 243    
Data columns (total 7 columns):    
 #   Column      Non-Null Count  Dtype      
---  ------      --------------  -----      
 0   total_bill  244 non-null    object     
 1   tip         244 non-null    float64    
 2   sex         244 non-null    object     
 3   smoker      244 non-null    object     
 4   day         244 non-null    object     
 5   time        244 non-null    object     
 6   size        244 non-null    int64 
Run Code Online (Sandbox Code Playgroud)

因此,这将会失败,因为第一行数据中有一个 XXX,其中的数字应该是:

tips['tip_pct'] = tips['tip'] / (tips['total_bill'] - tips['tip'])
Run Code Online (Sandbox Code Playgroud)

如何重写上面的行以过滤掉坏行,而不实际更改 DataFrame 的内容?

sop*_*les 5

pd.to_numeric您可以使用来包装具有“xxx”的列errors='coerce'。这会将字符串类型值转换为,NaN以便您的操作可以发生并且您的数据框将保持不变

tips['tip_pct'] = tips['tip'] / (pd.to_numeric(tips['total_bill'],errors='coerce') - tips['tip'])

  total_bill   tip     sex   smoker  day     time        size     p_pct
0        xxx  1.01  Female     No  Sun     Dinner           2       NaN
1      10.34  1.66    Male     No  Sun     Dinner           3  0.191244
2      21.01  3.50    Male     No  Sun     Dinner           3  0.199886
3      23.68  3.31    Male     No  Sun     Dinner           2  0.162494
4      24.59  3.61  Female     No  Sun     Dinner           4  0.172069
Run Code Online (Sandbox Code Playgroud)