2

I have a dataframe I've parsed out of a larger frame that looks like:

Contract Date
2012.0
2011.0
2011.0
2010.0
1312.0
1235.0
1235.0
1235.0
1230.0
.
.
111.0
111.0
110.0
110.0

I've converted the entire thing to strings so that I can slice the values because these dates are in a very strange format.

Basically the 2012.0 - 2010.0 are December of each year (2012 - 2010) but the dates like 1235.0 and 110.0 are in MMYY format - 1235.0 is Dec 2035 and 110.0 is Jan 2010.

What I want is to make a simple loop to iterate over these dates and translate them into months and year based off the conditions that I described above. I tried obtaining the month first using a poorly made attempt at using iterrows:

for index, row in contract.iterrows():
    if len(row) > 4:
        contract['Month'] = contract['Contract_Exp_Date'].str[:2]
    else:
        contract['Month'] = contract['Contract_Exp_Date'].str[:1]

But this did not work and loops for an exaggerated amount of time - probably because I need to be appending to a new column and not creating a new column Month every iteration.

How can I loop through each row and scrape both the month and the year based off the conditions I mentioned above correctly?

1 Answer 1

1

No need condition, just use logic of everything but last three characters, so logic written:

2018.0
   ^^^
   removed
111.0
  ^^^
  removed

So use:

df['Contract']=df['Contract'].str[:-3]

And now:

print(df['Contract'])

Is:

0     201
1     201
2     201
3     201
4     131
5     123
6     123
7     123
8     123
9      11
10     11
11     11
12     11
Name: Contract, dtype: object
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.