Python:如何从pandas系列的字典中获取值

2024-05-19 13:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python很陌生,我试图从字典中获取值,字典中的键是在dataframe列(pandas)中定义的。我找了好几次,最接近的是 以下链接中的问题,但没有给出答案。

所以,在这里我试图找到相同类型问题的答案。

Select from dictionary using pandas series

我有一本字典

type_dict = {3: 'foo', 4:'bar',5:'foobar', 6:'foobarbar'}

以及具有以下列的数据帧:

>>> df.type
0     3
1     4
2     5
3     6
4     3
5     4
6     5
7     6
8     3

我想创建一个新列,其中包含相应的type_dict值,但以下是我能找到的唯一不起作用的内容:

type_dict[df.type]

TypeError:“Series”对象是可变的,因此不能散列

type_dict[df.type.values]

类型错误:不可更改的类型:“numpy.ndarray”

更新问题:

对于pandas数据帧,比如说“df”,我如何用类型作为标记字典的键来绘制米上的速度。

mkr_dict = {'gps': 'x', 'phone': '+', 'car': 'o'}

x = {'speed': [10, 15, 20, 18, 19], 'meters' : [122, 150, 190, 230, 300], 'type': ['phone', 'phone', 'gps', 'gps', 'car']}

df = pd.DataFrame(x)
   meters  speed   type
0     122     10  phone
1     150     15  phone
2     190     20    gps
3     230     18    gps
4     300     19    car

plt.scatter(df.meters, df.Speed, marker = df.type.map(mkr_dict)) 

散点图对我不起作用。。。


Tags: 数据答案类型pandasdf字典typephone
2条回答

在熊猫身上,这应该管用

df['val'] = df.apply(lambda x: type_dict[x['type']], axis=1)

将dict作为参数传递给^{}

In [79]:

df['type'].map(type_dict)
Out[79]:
0          foo
1          bar
2       foobar
3    foobarbar
4          foo
5          bar
6       foobar
7    foobarbar
8          foo
Name: type, dtype: object

这将查找dict中的键值并从dict返回相关的值

相关问题 更多 >