Generation

generate functionMon, 20 Feb 2023

The 'Size' column of the Pandas dataframe contains data in the following format: Size 19M 14M 8.7M 25M 250k 429k 728k 3M Write a function that uses regex to convert strings: - that end in 'M' to a number with 5 zeros (e.g. 2.8M should be changed to 2800000) - that end in 'k' to a number with 3 zeros (for example, 429k should be changed to 429000)

import re def convert_size(size): if size[-1] == 'M': return int(float(size[:-1]) * 1000000) elif size[-1] == 'k': return int(float(size[:-1]) * 1000) else: return int(size) replaces = lambda x: convert_size(x) data['Size'] = data['Size'].apply(convert_size)

Questions about programming?Chat with your personal AI assistant