2

I have a large csv file where I have filtered out the rows I want and created smaller more manageable data frames (called 'CL'). Each row has a Contract Month and Contract Year both in Int64 (I believe). I want to create a column combining the two in a date format (e.g., MM-YYYY) and having difficulty.

I have tried both extracting the columns to pandas series and converting to string

series.to_string

as well as the individual columns with

CL['CONTRACT MONTH']= CL['CONTRACT MONTH'].astype(str)

The latter method gives me a message "... SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"

A little over my head with this (just learning Python) and was hoping for some help.

1
  • Would you want to store the combined date as an integer? Commented Jul 2, 2018 at 17:20

1 Answer 1

3

You can concatenate strings within Pandas series using +. In addition, you can use pd.Series.str.zfill to ensure months always have 2 characters:

df = pd.DataFrame([[10, 1995], [3, 1996], [2, 1998], [5, 2000]],
                  columns=['MONTH', 'YEAR'])

df['DATE'] = df['MONTH'].astype(str).str.zfill(2) + '-' + df['YEAR'].astype(str)

print(df)

   MONTH  YEAR     DATE
0     10  1995  10-1995
1      3  1996  03-1996
2      2  1998  02-1998
3      5  2000  05-2000

Your SettingWithCopyWarning may not represent a problem per se. It is often a guess by Pandas that you are operating on a copy rather than a view. You may safely ignore this warning if you see it with the above solution.

Sign up to request clarification or add additional context in comments.

2 Comments

one little snag...if I would want the new 'Date' to be come the index how would I do it? I tried df.set_index(df['DATE']) but doesn't work.
@ChrisL, Reassign back to df, i.e. df = df.set_index(df['DATE'])

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.