pandas Python - 从字符串中删除小数和零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46774069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:38:51  来源:igfitidea点击:

Python - Remove decimal and zero from string

pythonpandas

提问by Dread

I'm reading several spreadsheets into a data frame and there is an ID field that is a string in some spreadsheets and a number in others. I've converted it into a string, which is the data type I need, but I'm ending up with some IDs that have a ".0" at the end. How do I remove the decimal and zero?

我正在将几个电子表格读入一个数据框中,并且有一个 ID 字段,它在某些电子表格中是一个字符串,在其他电子表格中是一个数字。我已将其转换为字符串,这是我需要的数据类型,但我最终得到了一些末尾带有“.0”的 ID。如何删除小数和零?

Example: ID number 805096730.0 should be 805096730

示例:ID 号 805096730.0 应为 805096730

回答by jezrael

Use astypewith replace:

使用astypereplace

df = pd.DataFrame({'ID':[805096730.0,805096730.0]})

df['ID'] = df['ID'].astype(str).replace('\.0', '', regex=True)
print (df)
          ID
0  805096730
1  805096730

Or add parameter dtype:

或添加参数dtype

df = pd.read_excel(file, dtype={'ID':str})

回答by Boris M

Check type of your numbers before converting them to strings. It seems that they are floats, rather than integers. If this is the case, convert your numbers to integers:

在将它们转换为字符串之前检查数字的类型。似乎它们是浮点数,而不是整数。如果是这种情况,请将您的数字转换为整数:

df = pd.DataFrame([123.0, 456.0])
df = df.apply(int, axis=1)

0    123
1    456

Then, convert it into strings:

然后,将其转换为字符串:

df = df.apply(str)
print(df.iloc[1])

'456'