3

I am playing with the data set from FIFA 19 and currently trying to convert string value, wage and release clauses into float values e.g. €110.5M into 110500000. Here is my function which takes text as an argument and returns float value:

def text_to_num(text):
    d = {'K': 3, 'M': 6, 'B': 9}
    new_text = text[1:]
    if new_text[-1] in d:
        num = new_text[:-1]
        magnitude = new_text[-1]
        return Decimal(num) * 10 ** d[magnitude]
    else:
        return Decimal(new_text)

It's quite easy to apply it on single column, e.g. Value:

def convert_into_float(data):
    data['Value'] = data['Value'].apply(text_to_num)
    return data

I am wondering, how to convert all 3 columns at once instead of using above function three times.

def main():
    # load the data from .csv file, use ID column as index  
    new_data = load_data("data.csv", 'ID') 
    new_data = convert_into_float(new_data)

1 Answer 1

1

You can use DataFrame.applymap with filtered columns by list:

def convert_into_float(data):
    cols = ['col1','col2','col3']
    data[cols] = data[cols].applymap(text_to_num)
    return data
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.