3

I am not very knowledgeable in pandas

So I have a problem which is the following :

I want to get the number of days based on string column

Period
3 days
5 weeks
1 year

I want to convert this column into an integer which is the number of days like this:

Days
3 
35 
365 

I have done as follow:

def toDays(dt):
    if 'year' in dt:
        for s in dt:
            if s.isdigit():
                return int(s)*360  
    elif 'month' in dt:
        for s in dt:
            if s.isdigit():
                return int(s)*30
    elif 'week' in dt:
        for s in dt:
            if s.isdigit():
                return int(s)*7 
    if 'day' in dt:
        for s in dt:
            if s.isdigit():
                return int(s)   

train_file["Days"]=train_file["Periods"].map(toDays)

but that didn't work I would some help in order to map this function into the dataframe

1 Answer 1

5

Code -

import pandas as pd


def convert(s):
    ls = s.split()
    d = {'day': 1, 'week': 7, 'month': 30, 'year': 360}
    for k, v in d.items():
        if ls[1].startswith(k):
            return int(ls[0]) * v

df = pd.DataFrame({'Col': ['3 days', '5 weeks', '1 year']})

df['Col'] = df['Col'].apply(convert)

print(df)

Output -

   Col
0    3
1   35
2  360
Sign up to request clarification or add additional context in comments.

1 Comment

Isn't a way to map the Serie instead of creating a DataFrame?

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.