我正在尝试转换整数列表中的字符串列表,该列表将其ID关联到数据帧列中
这是因为我需要像下一个节目一样,按id绘制一个运动列表。有些运动不在JSON中。在这种情况下,有必要删除所需dataframe with integer list列中的该元素
这就是我必须映射的JSON:
[
{
"id": 1,
"name": "Karate",
},
{
"id": 2,
"name": "Paintball",
},
{
"id": 3,
"name": "Rugby",
},
{
"id": 4,
"name": "Squash",
},
{
"id": 5,
"name": "Softball",
},
{
"id": 6,
"name": "Swimiming",
},
{
"id": 7,
"name": "Weighlifting",
},
{
"id": 8,
"name": "Table Tennis",
},
{
"id": 9,
"name": "Tenpin Bowling",
}
]
这就是我拥有的数据框架,其中包含JSON中没有的运动
id sports
111 ['Softball', 'Table Tennis', 'Rafting']
222 ['Rugby', 'Tenpin Bowling','Squash']
333 ['Weighlifting', 'Tennis', 'Swimiming']
444 ['Softball', 'Table Tennis', 'Paintball']
555 ['Rugby', 'Tenpin Bowling','Squash']
666 ['Weighlifting', 'Karate', 'Swimiming']
777 ['Softball', 'Table Tennis', 'Soccer']
888 ['Basketball', 'Tenpin Bowling','Squash']
999 ['Weighlifting', 'Karate', 'Swimiming']
这就是我需要的数据帧,没有无法在JSON中映射的运动
id sports
111 [5, 8]
222 [3, 9, 4]
333 [7, 6]
444 [5, 8, 2]
555 [3, 9, 4]
666 [7, 1, 6]
777 [5, 8]
888 [9, 4]
999 [7, 1, 6]
有解决办法吗
提前谢谢
这与你之前的问题类似。我修改了我以前的答案来处理这个案例和
NaN
和非列表元素。让我们将json字符串称为l_str
test.json
中,请将其加载到data
data
李>sports
列中的值是列表,而不是字符串sports
列内容是字符串,则使用df.sports = df.sports.apply(literal_eval)
sports
列,请使用df['sports'] =
而不是df['codes'] =
首先从json} 和^{} 从json
data
中初始化数据帧并使用^{data
中创建mappings
字典,然后使用该mappings
字典将列表中的每个运动映射到相应的id
:或者,也可以将^{} 与^{} 一起使用,但这种方法通常速度较慢:
结果:
相关问题 更多 >
编程相关推荐