jh1*_*h10 7 python dictionary dataframe pandas
我有一本字典,我想将它映射到当前数据框并创建一个新列。我在元组中有键,它映射到我的数据框中的两个不同列。
dct = {('County', 'State'):'CountyType'}
df = pd.DataFrame(data=['County','State'])
Run Code Online (Sandbox Code Playgroud)
我想创建一个新的列,CountyType
使用dict
映射到两列中df
。但是,执行以下操作会给我一个错误。这还能怎么做?
df['CountyType'] = (list(zip(df.County,df.State)))
df = df.replace({'CountyType': county_type_dict)
Run Code Online (Sandbox Code Playgroud)
您可以MultiIndex
从两个系列创建一个,然后映射。来自@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
Run Code Online (Sandbox Code Playgroud)
如果您有以下字典,其中元组作为键,并且DataFrame
具有与元组值对应的列
import pandas as pd
dct = {('A', 1): 'One', ('B', 2): 'Two', ('B', 3): 'Three'}
df = pd.DataFrame({'County': ['A', 'A', 'B', 'B', 'B'],
'State': [1, 2, 1, 2, 3]})
Run Code Online (Sandbox Code Playgroud)
Series
您可以从您的元组中创建一个df
,然后使用.map()
df['CountyType'] = pd.Series(list(zip(df.County, df.State))).map(dct)
Run Code Online (Sandbox Code Playgroud)
结果是
County State CountyType
0 A 1 One
1 A 2 NaN
2 B 1 NaN
3 B 2 Two
4 B 3 Three
Run Code Online (Sandbox Code Playgroud)