[英]Insert a comma as thousands separator between several pandas df columns
I am trying to have a comma thousands separator for easier viewing in several columns of my pandas df.我正在尝试使用逗号千位分隔符,以便在我的 pandas df 的几列中查看。
My question builds upon this question+answer.我的问题建立在这个问题+答案之上。 But I want to apply it to several columns and I fail.
但我想将它应用到几列,但我失败了。
A minimal example:一个最小的例子:
# 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)
Would greatly appreciate if somebody could show me the way.如果有人能给我指路,将不胜感激。 Note that I want to apply this function to several dozen columns, so manually repeating the code for every column is not the solution.
请注意,我想将此 function 应用于几十列,因此手动重复每一列的代码不是解决方案。
Use DataFrame.applymap
with list of columns names for processing:使用
DataFrame.applymap
和列名列表进行处理:
np.random.seed(2020)
df = pd.DataFrame({'a' : np.random.normal(200000, 10000, 6),
'c' : np.random.normal(200000, 100000, 6)})
cols = ['a', 'c']
df[cols] = df[cols].applymap("{:,}".format)
print (df)
a c
0 182,311.5429442405 193,884.55680466516
1 200,755.5227120811 206,451.38441186142
2 188,693.70297194656 241,011.29497994468
3 193,485.69833095264 142,711.7509918912
4 191,068.843736801 119,866.63751387625
5 187,258.9902320009 331,203.5192212922
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.