I'm going a little further this previous question about mapping dictionary values to dataframes. I have a simple dataframe df like:

我将进一步讨论将字典值映射到数据帧的上一个问题。我有一个简单的数据帧df,如:

U,id
111,01
112,02
112,03
113,04
113,05
113,06
114,07

and I want to map on a new column the following nested dictionary:

我想在新列上映射以下嵌套字典:

d = {112: {'en': 1, 'es': 2}, 113: {'zh': 1, 'ja': 1, 'es': 2}, 114: {'es': 1}, 111: {'ar': 2, 'en': 1}}

taking into account only the most frequent L values, i.e. 112:'es', 113:'es', 114:'es', 111:'ar'.

只考虑最常见的L值,即112:'es',113:'es',114:'es',111:'ar'。

On a simple dictionary case, I can use df['C'] = df['U'].map(d). How can I do the same taking only the previous highest values? The resulting dataframe would appear as:

在一个简单的字典案例中,我可以使用df ['C'] = df ['U']。map(d)。我怎样才能只采用以前的最高值?生成的数据框将显示为:

U,id,C
111,01,ar
112,02,es
112,03,es
113,04,es
113,05,es
113,06,es
114,07,es

1 个解决方案

#1


I'd flatten the dict to create a new dict and then you can call map as before:

我将dict压平以创建一个新的dict然后你可以像以前一样调用map:

In [44]:

max_d={}
for k,v in d.items():
    max_d[k] = max(v, key=v.get)
max_d
Out[44]:
{111: 'ar', 112: 'es', 113: 'es', 114: 'es'}
In [45]:

df['C'] = df['U'].map(max_d)
df  
Out[45]:
     U  id   C
0  111   1  ar
1  112   2  es
2  112   3  es
3  113   4  es
4  113   5  es
5  113   6  es
6  114   7  es

更多相关文章

  1. python 读写json数据
  2. python编程之一:使用网格索引算法进行空间数据查询
  3. Python基本数据结构
  4. 【原创】Python处理海量数据的实战研究
  5. 后端传给前端int 类型数据自增或自减
  6. qpython 读入数据问题: EOF error with input / raw_input
  7. 变量和数据类型
  8. 将2d数组数据视为定义形状的像素——是否可能创建内部和表面?
  9. Python数据分析学习笔记

随机推荐

  1. 请教用sql loader导入数据,最后一位是整数
  2. JDBC连接并使用mysql数据库
  3. SQL Server 2008使用sproc中的函数
  4. 如何在ACCESS中接收SQL SERVER返回结果集
  5. 脚本与SQL Server中的表并发运行
  6. logstash-jdbc-input与mysql数据库同步
  7. 求查询成绩表中两门科成绩90分以上的学生
  8. SQL Server Reporting Services图表查询
  9. Python将MySQL表数据写入excel
  10. SQL当执行插入操作时,字符串含有''的时候