如何使用列名格式化熊猫中的列

时间:2019-04-30 12:31:30

标签: python pandas formatting

一旦我将df发送到_excel,我想格式化数据框中的列,使其在大数字之间具有','。我有一个有效的代码,但它根据其位置选择列。我希望代码根据其名称而不是位置来选择该列。有人可以帮我吗?

df.to_excel(writer, sheet_name = 'Final Trade List')

wb = writer.book
ws = writer.sheets['Final Trade List']

format = wb.add_format({'num_format': '#,##'})

ws.set_column('O:O', 12, format) # this code works but its based on position and not name

ws.set_column(df['$ to buy'], 12, format) # this gives me an error

writer.save()

TypeError: cannot convert the series to <class 'int'>

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

import pandas as pd
df['columnname'] = pd.Series([format(val, ',') for val in df['columnname']], index = df.index)