How do I insert a duplicated column in a pandas dataframe with the last 3 numbers removed from the values of the new column?

Viewed 497

I'm extremely new to this. I have values in a column called "oldcol". I'm trying to create a new dataframe that has oldcol and a new column with the same values as in oldcol except with the last three digits of the string removed. I thought I could use the insert method but realized from the documentation that I couldn't just bring over the oldcol values that way. The code I was attempting is below:

### I realize this is not going to work.
df2 = df1.insert(2,
                 column='newcol',
                 value='oldcol')
df2['newcol'] = df2['newcol'] \
    .astype(str).str[:-3] \
        .astype(np.int64)

What would be the best way to go about this?

1 Answers

Try this:

df['new_col'] = df['old_col'].str[:-3]

This should do the job. Let me know if it works.

Related