[英]How do I custom format a pandas integer column to display with commas as thousands separators?
[英]Pandas Series/Dataframe: Format string numbers with commas as Thousands Separators
假设我有以下当前类型为 object 的系列:
s = {'A': "Hello", 'B': "593753", 'C': "16.8|", "D" : np.nan, "E":"%"}
s = pd.Series(data=s, index=['A', 'B', 'C',"D","E"])
我想使用逗号作为千位分隔符格式化数字。
我使用以下方法转换了系列:
s2 = pd.to_numeric(s, errors="coerce")
这当然会将 dtype 更改为float
。 将系列转换回 object 会再次删除逗号。
有没有办法格式化存储为字符串的数字,以便它们有逗号作为千位分隔符? 最后,该系列必须是 object 类型,因为我需要能够使用df.str.contains()
在系列中搜索“,”
使用应用 lambda 的解决方案
import pandas as pd
import numpy as np
def format_float(x):
try:
flt = float(x)
return "{:,}".format(flt)
except:
return x
s = {'A': "Hello", 'B': "593753", 'C': "16.8|", "D" : np.nan, "E":"%"}
s = pd.Series(data=s, index=['A', 'B', 'C',"D","E"])
s2 = s.apply(lambda x: format_float(x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.