小编lcv*_*end的帖子

将字典中的值映射到 Pandas 列的子集的最快方法是什么?

我有一个包含调查问卷数据的数据框。某些答案的分数需要倒转以进行进一步分析。所以我想做的是:

\n\n
    \n
  1. 选择有问题的行,其中分数要倒转;
  2. \n
  3. 使用字典将分数映射到新分数。
  4. \n
\n\n

我的数据框中的所有相关列都是dtype“类别”。下面,我设置了一个简化的示例来说明我想要完成的任务:

\n\n
import pandas as pd\n\n# create a list of scores and a dictionary to invert the scores:\nlst = ['u', 'v', 'w', 'x', 'y']\nlst_rev = list(reversed(lst))\ndct = dict(zip(lst, lst_rev))\n\n# create the example dataframe:\ndf = pd.DataFrame({'A':['a', 'b', 'a', 'c', 'a'],\n                   'B':lst},\n                   dtype='category')\n\n# create a list for selecting the specific rows that need to be remapped:\nsel = ['b', 'c']\n
Run Code Online (Sandbox Code Playgroud)\n\n

第一种方法

\n\n

我尝试过的第一种方法:

\n\n
%timeit df['B'] = df.apply(lambda x: dct.get(x['B']) if x['A'] …
Run Code Online (Sandbox Code Playgroud)

python pandas

2
推荐指数
1
解决办法
1568
查看次数

标签 统计

pandas ×1

python ×1