Python中文
首页
教程
问答
标签
搜索
登录
注册
如何将值从嵌套字典映射到dataframe中的多列,或从3列dataframe映射到主dataframe?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>例如:我有这样的df:</p> <pre><code>id Status Country Income 1 4 2 3 2 5 3 2 </code></pre> <p>像这样的字典:</p> <pre><code>d_dict = {Status : { '4':'Married', '5':'UnMarried'}, Country: { '2': 'Japan' , '3': 'China'}, Income: {'3': "5000-10000", 2: "11000-20000"}} </code></pre> <p>我想基于嵌套字典映射这些值。我可以为这样一个专栏做:</p> <pre><code>for k,v in d_dict.items(): max_d[k] = max(v, key=v.get) df['Status'] = df['Status'].map(max_d) </code></pre> <p>但我有2000多列,我不知道如何才能处理多个列</p> <p>我也尝试了替换,但不起作用</p> <pre><code>df=df.astype(str).replace(d_dict) </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>如果我理解正确,您可以使用:</p> <pre><code> for k in d_dict.keys(): df[k] = df[k].apply(lambda x: d_dict[k][str(x)]) </code></pre> <p>但请注意,dict键必须是字符串(因此str(x)而不是x),否则会引发错误</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何用强化学习更新函数逼近中的权重?
5 回答
如何用归并排序计算倒数?
9 回答
如何用当前数据拟合正弦波?
2 回答
如何用当前页面的值填充表单?
8 回答
如何用彩色地图在2dpython直方图中勾勒出箱子的轮廓?
2 回答
如何用彩色地图给等高线标签上色?
4 回答
如何用彩色打印到控制台?
6 回答
如何用彩色条绘制2d直方图,在Python中显示第三个变量的平均值?
2 回答
如何用彩色条绘制直方图,其中的颜色应与xaxis中的值一致?
1 回答
如何用彩色贴图填充曲线和原始边之间的区域?
8 回答
如何用循环分割数组并对其应用操作?
5 回答
如何用循环创建多个子集的数据帧
10 回答
如何用循环和递归实现求和
6 回答
如何用循环填充数组?
4 回答
如何用循环当前引用的位置更新变量?
6 回答
如何用循环求这个级数的和
4 回答
如何用循环解这个方程?
1 回答
如何用循环语句逐个读取数据帧中的数据?
6 回答
如何用循环除法?(Python)
5 回答
如何用感知一致性对HSV空间进行采样
7 回答