【问题标题】:Insert a comma as thousands separator between several pandas df columns在几个 pandas df 列之间插入逗号作为千位分隔符
【发布时间】: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的列

标签: python pandas apply


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多