【发布时间】:2015-07-30 12:14:54
【问题描述】:
我对 python 非常陌生,并试图从字典中获取值,其中键定义在数据框列 (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]
TypeError: unhashable type: 'numpy.ndarray'
更新问题:
对于 pandas DataFrame,比如“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))
散点图对我不起作用...
【问题讨论】:
-
AFAIK,普通 python 没有“数据帧”的概念。如果您使用的是框架或库(如 pandas),请指明是哪一个。
-
我认为您的 scatter 问题应该是一个新问题,我不是 matplotlib 专家,但我认为您可以使用此处的答案来实现它:stackoverflow.com/questions/26490817/… 基本上这会遍历每一行调用 scatter 和传递 x,y 坐标和标记样式
标签: python dictionary pandas key dataframe