Home > front end >  Python add column with new value when 2 conditions match
Python add column with new value when 2 conditions match

Time:10-26

I am trying to add a new column to my data with a FIPS code in it (5 digit number). Basically when County from maindata.csv matches County from fipsdata.tsv, I want the FIPS code (fipsCountyFIPS) to land in a new column i.e. data[fips] (so if County in maindata matches County in fipsdata THEN write the corresponding fips code to a new column in dataframe).

data = pd.read_csv ("maindata.csv")
fips = pd.read_csv ("fips2county.tsv",sep='\t')

data[fips] = np.where(data.County == fips.CountyName, fipsCountyFIPS)

I also experimented with the following which sounds like it should be easier in theory, though I couldn't work it out :( enter image description here

If one or more "Counties" not found inside fips:

enter image description here

  • Related