Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

pandas - Mapping Python dictionary with multiple keys into dataframe with multiple columns matching keys

I have a dictionary that I would like to map onto a current dataframe and create a new column. I have keys in a tuple, which map onto two different columns in my dataframe.

dct = {('County', 'State'):'CountyType'}
df = pd.DataFrame(data=['County','State'])

I would like to create a new column, CountyType, using dict to map onto the two columns in df. However, doing the following gives me an error. How else could this be done?

df['CountyType'] = (list(zip(df.County,df.State)))
df = df.replace({'CountyType': county_type_dict)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a MultiIndex from two series and then map. Data from @ALollz.

df['CountyType'] = df.set_index(['County', 'State']).index.map(dct.get)

print(df)

  County  State CountyType
0      A      1        One
1      A      2       None
2      B      1       None
3      B      2        Two
4      B      3      Three

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...