【问题标题】:How to use a list as index in dataframe.map()?如何在 dataframe.map() 中使用列表作为索引?
【发布时间】:2021-11-04 20:53:27
【问题描述】:

我有一个看起来像这样的 pandas df:

ld_r2_array_df.head()
         SNP_A                  r2_ld_array
0  1:203337500  [1, NONE, NONE, NONE, NONE]
1   20:6730358  [1, NONE, NONE, NONE, NONE]
2   7:50878411  [1, NONE, NONE, NONE, NONE]
3  20:47025897  [1, NONE, NONE, NONE, NONE]
4   18:7553626  [1, NONE, NONE, NONE, NONE]

还有一个字典:

print(dict(list(csnps_indices.items())[0:2]))
{'10:100148542': [4582], '10:10091912': [4527]}

当我运行下面的命令时,

ld_r2_array_df["order"] = ld_r2_array_df.SNP_A.map(csnps_indices)

我收到此错误:

Traceback (most recent call last):
  File "pandas/_libs/hashtable_class_helper.pxi", line 4588, in pandas._libs.hashtable.PyObjectHashTable.map_locations
TypeError: unhashable type: 'list'
Exception ignored in: 'pandas._libs.index.IndexEngine._call_map_locations'

我是一个完整的 python 新手,所以我想知道这里可能是什么问题。我已经尝试将 dict 转换为元组,但随后又收到另一个错误:

TypeError: 'type' object is not subscriptable

如果我应该提供更多信息以重现错误,请告诉我。谢谢!

【问题讨论】:

  • csnps_indices的类型是什么?
  • 退后一步,你希望在这里做什么?您是否尝试使用那里的字符串值('10:100148542'} 在数据框中查找一行?
  • print(type(csnps_indices)):
  • 我想根据字典中的索引将某些行保留在我的数据框中,然后我将根据订单值对它们进行排序。
  • 请尝试使用匹配的输入和输出更新您的帖子

标签: python pandas list


【解决方案1】:

您的代码似乎对我有用。

输入数据:

>>> df
         SNP_A                  r2_ld_array
0  1:203337500  [1, NONE, NONE, NONE, NONE]
1   20:6730358  [1, NONE, NONE, NONE, NONE]
2   7:50878411  [1, NONE, NONE, NONE, NONE]
3  20:47025897  [1, NONE, NONE, NONE, NONE]
4   18:7553626  [1, NONE, NONE, NONE, NONE]

>>> d
{'1:203337500': [4582], '7:50878411': [4527]}

尝试映射:

df['order'] = df['SNP_A'].map(d)
print(df)

# Output:
         SNP_A                  r2_ld_array   order
0  1:203337500  [1, NONE, NONE, NONE, NONE]  [4582]
1   20:6730358  [1, NONE, NONE, NONE, NONE]     NaN
2   7:50878411  [1, NONE, NONE, NONE, NONE]  [4527]
3  20:47025897  [1, NONE, NONE, NONE, NONE]     NaN
4   18:7553626  [1, NONE, NONE, NONE, NONE]     NaN

【讨论】:

  • 我将“ld_r2_array_df.SNP_A”表示法更改为“df['SNP_A']”,现在确实将“订单”列添加到我的 df 中。这是某种python版本问题吗?奇怪的是,我一直收到相同的错误消息,但这次我的脚本一直在运行。
  • 好的,它适用于 anaconda/3.2021.05,但不适用于 anaconda/3.2019.10。你用的是哪个 python 或 conda 版本?
  • @gokberk。 Python = '3.9.7',Pandas = '1.3.3' 和 Numpy = '1.21.2'。对于 Anaconda/3.2019,您的 Pandas 版本可能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 2015-07-10
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
相关资源
最近更新 更多