4 回答
TA贡献1860条经验 获得超9个赞
df['Gender'] = df.Name.map(lambda x: d[x][0]) df['Age'] = df.Name.map(lambda x: d[x][1])
TA贡献1900条经验 获得超5个赞
使用pd.DataFrame
构造函数 withSeries.map
并使用pd.concat
concat with df
:
In [2696]: df = pd.concat([df,pd.DataFrame(df.Name.map(d).tolist(), columns=['Gender', 'Age'])], axis=1)
In [2695]: df
Out[2696]:
Name Gender Age
0 Jack Male 22
1 Alex Male 26
2 Jackie Female 28
3 Susan Female 30
TA贡献1876条经验 获得超6个赞
取出字典中的所有值
d = {'Jack':['Male','22'],'Alex':['Male','26'],'Jackie':['Female','28'],'Susan':['Female','30']}
value_list = list(d.values())
df = pd.DataFrame(value_list, columns =['Gender', 'Age'])
print(df)
TA贡献1893条经验 获得超10个赞
如果字典中没有匹配项,解决方案也能正常工作,例如:
d = {'Alex':['Male','26'],'Jackie':['Female','28'],'Susan':['Female','30']}
print (df)
Name Gender Age
0 Alex Male 26
1 Jack NaN NaN
2 Jackie Female 28
3 Susan Female 30
DataFrame.from_dict
从字典中使用并添加到列Name
by DataFrame.join
,优点是输入数据中的更多列都以相同的方式工作:
df = df.join(pd.DataFrame.from_dict(d, orient='index', columns=['Gender','Age']), on='Name')
print (df)
Name Gender Age
0 Jack Male 22
1 Alex Male 26
2 Jackie Female 28
3 Susan Female 30
如果创建 2 个字典,您的解决方案应该有效:
d1 = {k:v[0] for k,v in d.items()}
d2 = {k:v[1] for k,v in d.items()}
df['Gender'] = df.Name.map(d1)
df['Age'] = df.Name.map(d2)
print (df)
Name Gender Age
0 Jack Male 22
1 Alex Male 26
2 Jackie Female 28
3 Susan Female 30
添加回答
举报