Python - 从字符串中删除十进制和零

时间:2017-10-16 15:40:39

标签: python pandas

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

示例:ID号805096730.0应为805096730

2 个答案:

答案 0 :(得分:9)

astype使用replace

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

或添加参数dtype

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

答案 1 :(得分:1)

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

>>> year_counts = {(name, code): count for (name, code, count) in year}
>>> month_counts = {(name, code): count for (name, code, count) in month}
>>> week_counts = {(name, code): count for (name, code, count) in week}
>>> all_cities = [(name, code) for (name, code, count) in set(year + month + week)]
>>> [(x[0], x[1], year_counts.get(x, 0), month_counts.get(x, 0), week_counts.get(x, 0)) for x in all_cities]
[('Chittendon', '3367', 0, 1, 1),
 ('Windham', '3457', 1, 0, 0),
 ('Fanklin Grand Isle', '5560', 1, 1, 1)]

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

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

0    123
1    456
相关问题