Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从熊猫系列中有选择地删除字符串?_Python_Pandas_String_Jupyter Notebook - Fatal编程技术网

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'-$,'')
适用于您。