如何更改 excel 电子表格中某些列的数字格式?
How to change the number formatting of certain columns in an excel spreadsheet?
我想删除美元符号格式,$###,##0.00
并将其替换为 #,##0.00
数字格式。
我试过只更改 sheet 中一个单元格的格式,但我不知道它是否正在执行任何操作,因为文件中没有任何更改。
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb['example']
sheet('E7').number_format = '#,##0.00'
我希望输出将 E7 的值从 $380.00 更改为 380.00,但我收到 TypeError: 'Worksheet' object is not callable
和文件没有任何变化。
对于单个单元格:
import re
f_clean = lambda x: re.sub('[$\-,\|]', '', x)
f_float = lambda x: float(x) if x!='' else np.NaN
print(f_float(f_clean(',000.00')))
# 10000.0
对于整列:
# Here's a solution I use for large datasets:
import re
def lookup_money(s):
"""
This is an extremely fast approach to parsing currency to floats.
For large data, the same currencies are often repeated. Rather than
re-parse these, we store all unique values, parse them, and
use a lookup to convert all figures.
(Should be 10X faster than without lookup dict)
"""
f_clean = lambda x: re.sub('[$\-,\|]', '', x)
f_float = lambda x: float(x) if x!='' else np.NaN
currencies = {curr:f_float(f_convert(curr)) for curr in s.unique()}
return s.map(currencies)
# apply to some df as such:
# df['curr'] = df['curr'].apply(lookup_money)
我想删除美元符号格式,$###,##0.00
并将其替换为 #,##0.00
数字格式。
我试过只更改 sheet 中一个单元格的格式,但我不知道它是否正在执行任何操作,因为文件中没有任何更改。
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb['example']
sheet('E7').number_format = '#,##0.00'
我希望输出将 E7 的值从 $380.00 更改为 380.00,但我收到 TypeError: 'Worksheet' object is not callable
和文件没有任何变化。
对于单个单元格:
import re
f_clean = lambda x: re.sub('[$\-,\|]', '', x)
f_float = lambda x: float(x) if x!='' else np.NaN
print(f_float(f_clean(',000.00')))
# 10000.0
对于整列:
# Here's a solution I use for large datasets:
import re
def lookup_money(s):
"""
This is an extremely fast approach to parsing currency to floats.
For large data, the same currencies are often repeated. Rather than
re-parse these, we store all unique values, parse them, and
use a lookup to convert all figures.
(Should be 10X faster than without lookup dict)
"""
f_clean = lambda x: re.sub('[$\-,\|]', '', x)
f_float = lambda x: float(x) if x!='' else np.NaN
currencies = {curr:f_float(f_convert(curr)) for curr in s.unique()}
return s.map(currencies)
# apply to some df as such:
# df['curr'] = df['curr'].apply(lookup_money)