【发布时间】:2020-10-26 09:13:21
【问题描述】:
我正在尝试使用逗号千位分隔符,以便在我的 pandas df 的 几个 列中更轻松地查看。
我的问题基于this question+answer。但我想将它应用于多个列,但我失败了。
一个最小的例子:
# A random df
df = pd.DataFrame({'a' : np.random.normal(200000, 10000, 6),
'c' : np.random.normal(200000, 100000, 6)})
# This works:
df['a'] = df.a.apply(lambda x : "{:,}".format(x))
# But this doesn't
df = df.apply(lambda x : "{:,}".format(x) if x.name in ['a', 'c'] else x)
如果有人能给我指路,将不胜感激。请注意,我想将此函数应用于几十列,因此手动重复每一列的代码不是解决方案。
【问题讨论】:
-
您可以通过
df[['a', 'b']].apply()选择您想要apply的列