Python 如何从熊猫系列中有选择地删除字符串?
我很难摆脱熊猫系列中的一根绳子。我想删除前两个“-”字符串,但想保留最后两个数字。下面是一个例子Python 如何从熊猫系列中有选择地删除字符串?,python,pandas,string,jupyter-notebook,Python,Pandas,String,Jupyter Notebook,我很难摆脱熊猫系列中的一根绳子。我想删除前两个“-”字符串,但想保留最后两个数字。下面是一个例子 import pandas as pd temp = pd.Series(['-', '-', '-0.3', '-0.9']) print(temp) Out[135]: 0 - 1 - 2 -0.3 3 -0.9 dtype: object 无法使用temp.str.replace(“-”,“”),因为它也会从最后两个数字目标中删除减号。有人能帮我吗。
import pandas as pd
temp = pd.Series(['-', '-', '-0.3', '-0.9'])
print(temp)
Out[135]:
0 -
1 -
2 -0.3
3 -0.9
dtype: object
无法使用temp.str.replace(“-”,“”)
,因为它也会从最后两个数字目标中删除减号。有人能帮我吗。提前谢谢 使用:
输出
0
1
2 -0.3
3 -0.9
dtype: object
0
1
2 -0.3
3 -0.9
dtype: object
或者简单地使用:
输出
0
1
2 -0.3
3 -0.9
dtype: object
0
1
2 -0.3
3 -0.9
dtype: object
可以将字符串转换为数字:
pd.to_numeric(temp, errors='coerce').fillna('')
输出:
0
1
2 -0.3
3 -0.9
您可以删除不需要的字符串,如下所示:
import pandas as pd
temp = pd.Series(['-', '-', '-0.3', '-0.9'])
# this will drop the string that match '-'
new_temp= temp[temp != '-']
print(new_temp)
输出:
2 -0.3
3 -0.9
dtype: object
参考资料:您可以使用正则表达式来更好地控制如何替换文本:
temp.str.replace(r'-$,'')
适用于您。