简体   繁体   English

Python 从 Pandas 数据框怪异的 output 中删除单引号

[英]Python Remove single quotes from Pandas data frame weird output

In my dataframe I have a string column as shown below在我的 dataframe 中,我有一个字符串列,如下所示

acctno
'12345
 12345
 12345-5678

I am trying to remove the Single quote(') in the Column.我正在尝试删除列中的单引号(')。 I ran the below code我运行了下面的代码

df['acctno'] = df['acctno'].str.replace("[']", "")

The output is not what i expected output 不是我所期望的

Output"输出”

acctno
12345
nan 
12345-5678

Trying to understand why 12345 value without single quotes is being removed instead of leaving it as it is.试图理解为什么没有单引号的 12345 值被删除而不是保持原样。 Any help appreciated!任何帮助表示赞赏!

If you intend the column to have only strings and got the integer input as error, you can also convert it to string before the clean up of single quote character, eg by:如果您希望该列仅包含字符串并将 integer 输入作为错误,您还可以在清理单引号字符之前将其转换为字符串,例如:

df['acctno'] = df['acctno'].astype(str).str.replace("[']", "", regex=True)

Demo演示

data = {'acctno': {0: "'12345", 1: 12345, 2: '12345-5678'}}
df = pd.DataFrame(data)

df['acctno'] = df['acctno'].astype(str).str.replace("[']", "", regex=True)


## Without NaN now 

       acctno
0       12345
1       12345
2  12345-5678

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM