Skip to main content
 首页 » 编程设计

python之如何从数据框列中删除拖尾字母表

2025年02月15日8birdshome

我有一个数据框:

A B 10.1 33.3 11.2 44.2 秒 12.3 11.3 秒 14.2秒 * 15.4 秒南

我想要输出为

A B 10.1 33.3 11.2 44.2 12.3 11.3 14.2 0 15.4 0

如何删除这些拖尾字母 我试过这段代码

1st approch:  

bulb_temp_df['A'].str.extract('(\d)').astype( float ) bulb_temp_df['B'].str.extract('(\d)').astype(float)

第二种方法:

bulb_temp_df['A'] = bulb_temp_df['A'].astype(str) bulb_temp_df['A'] = bulb_temp_df['A'].map(lambda x: x.rstrip('aAbBcC'))

这些都不起作用。他们没有从色谱柱中去除尾矿。

请您参考如下方法:

您可以提取floats首先将 NaN 替换为 0 添加 fillna .

解决方案在 apply 中用于处理多列。

cols = ['A','B'] 
 
#if mixed values - numeric with strings 
bulb_temp_df[cols]=bulb_temp_df[cols].astype(str) 
 
bulb_temp_df[cols]=bulb_temp_df[cols].apply(lambda x:x.str.extract('(\d+\.\d+)',expand=False) 
                                                      .astype(float) 
                                                      .fillna(0)) 
      A     B 
0  10.1  33.3 
1  11.2  44.2 
2  12.3  11.3 
3  14.2   0.0 
4  15.4   0.0