kylemaxim
kylemaxim

Reputation: 95

add substring to column if string in another column

I'm trying to manipulate a csv file with a series of dates which inconsistently use 'CE' and 'BCE' in one column or the other. Imagine a condensed example:

 ID,earliestdate, latestdate
 1,1st century, 2nd century CE
 2,3rd century, 2nd century BCE

How could I write a function that would join 'CE' to df['earliestdate'] if 'CE' in df['latestdate']?

Upvotes: 1

Views: 56

Answers (1)

Andrew Mascillaro
Andrew Mascillaro

Reputation: 948

You can use pandas indexing to check which rows have 'CE' in them and add 'CE' to the corresponding 'earliestdate' strings.

df.loc[df["latestdate"].str.endswith(" CE"), "earliestdate"] = \
    df.loc[df["latestdate"].str.endswith(" CE"), "earliestdate"].astype(str) +\
    " CE"

Upvotes: 1

Related Questions