Skip to main content
 首页 » 编程设计

python之pandas 系列查找具有特定作为最后一个字符的字符串

2025年05月04日17duanxz

我在 df 中有一列有一个减号,即 - 作为某些列字符串值中的最后一个字符。现在我想找到这些字符串,我想知道该怎么做,

df['amount'] 
0          3.60- 
1          1.70 
2          1.80 
3          1.20 
4          1.22- 
Name: amount, Length: 5, dtype: object 

所以对于每个字符串,我可以做

df['amount'][default_int_index] = df['amount'][default_int_index][-1:] + df['amount'][default_int_index][:-1] 

将 - 放在字符串的前面。所以结果看起来像,

0          -3.60 
1          1.70 
2          1.80 
3          1.20 
4          -1.22 

然后将整个系列转换成float64,

df['amount'] = df['amount'].astype(np.float64) 

请您参考如下方法:

使用 .str.endswith 即

mask = df['Amount'].str.endswith('-') 
0     True 
1    False 
2    False 
3    False 
4     True 
Name: Amount, dtype: bool 

For conditional replacement use np.where i.e

df['Amount'] = np.where(mask,'-'+df['Amount'].str[:-1],df['Amount']).astype(float) 

输出:

0   -3.60 
1    1.70 
2    1.80 
3    1.20 
4   -1.22 
Name: Amount, dtype: float64