从 pandas 中的浮点数中去除尾随小数点
Strip trailing decimal points from floats in pandas
我数据集中的所有列似乎都是浮点数。
有些包含像 '20 这样的值。 '或'11。 '
如何有选择地快速删除点和 space,而不影响列中的其他值,例如“24.4”或“12.5”?
我尝试了几种解决方案,但 none 都奏效了。
我的目标是改变,例如'12。 ' 到 '12',对于每个单元格中的每个值,其中 '. ' 出现。
您可以使用正则表达式替换 ie
df.replace('\.(?!\d)','',regex=True)
如果您有类似的数据框。
df = pd.DataFrame(['12.','13.','14.1','15.5'])
df.replace('\.(?!\d)','',regex=True) # inplace = True if you want to change main dataframe.
0
0 12
1 13
2 14.1
3 15.5
如果您的列包含字符串:
>>> a
0 1
0 1 12.
1 2 14.5
2 3 15.
3 4 16.3
>>> a[1]=[i.replace('. ', '') for i in a[1]]
>>> a
0 1
0 1 12
1 2 14.5
2 3 15
3 4 16.3
如果有 float 你可以创建一个混合类型(int 和 float)的新列表:
>>> b=[int(i) if i.is_integer() else float(i) for i in a[1]]
>>> b
[12, 14.5, 15, 16.3]
但你不能在数据框中这样做:
>>> a[1]=[int(i) if i.is_integer() else float(i) for i in a[1]]
>>> a
0 1
0 1.0 12.0
1 2.0 14.5
2 3.0 15.0
3 4.0 16.3
您可以为pandas设置自定义浮点数格式化函数,例如:
>>> import pandas as pd
>>> df = pd.DataFrame({'col1':[1, 2, 3], 'col2':[2.0, 1.0, 4.1]})
>>> pd.set_option('display.float_format', lambda x: ('%f' % x).rstrip('.0'))
>>> df
col1 col2
0 1 2
1 2 1
2 3 4.1
我数据集中的所有列似乎都是浮点数。 有些包含像 '20 这样的值。 '或'11。 '
如何有选择地快速删除点和 space,而不影响列中的其他值,例如“24.4”或“12.5”?
我尝试了几种解决方案,但 none 都奏效了。
我的目标是改变,例如'12。 ' 到 '12',对于每个单元格中的每个值,其中 '. ' 出现。
您可以使用正则表达式替换 ie
df.replace('\.(?!\d)','',regex=True)
如果您有类似的数据框。
df = pd.DataFrame(['12.','13.','14.1','15.5'])
df.replace('\.(?!\d)','',regex=True) # inplace = True if you want to change main dataframe.
0 0 12 1 13 2 14.1 3 15.5
如果您的列包含字符串:
>>> a
0 1
0 1 12.
1 2 14.5
2 3 15.
3 4 16.3
>>> a[1]=[i.replace('. ', '') for i in a[1]]
>>> a
0 1
0 1 12
1 2 14.5
2 3 15
3 4 16.3
如果有 float 你可以创建一个混合类型(int 和 float)的新列表:
>>> b=[int(i) if i.is_integer() else float(i) for i in a[1]]
>>> b
[12, 14.5, 15, 16.3]
但你不能在数据框中这样做:
>>> a[1]=[int(i) if i.is_integer() else float(i) for i in a[1]]
>>> a
0 1
0 1.0 12.0
1 2.0 14.5
2 3.0 15.0
3 4.0 16.3
您可以为pandas设置自定义浮点数格式化函数,例如:
>>> import pandas as pd
>>> df = pd.DataFrame({'col1':[1, 2, 3], 'col2':[2.0, 1.0, 4.1]})
>>> pd.set_option('display.float_format', lambda x: ('%f' % x).rstrip('.0'))
>>> df
col1 col2
0 1 2
1 2 1
2 3 4.1