我有一个包含调查问卷数据的数据框。某些答案的分数需要倒转以进行进一步分析。所以我想做的是:
\n\n我的数据框中的所有相关列都是dtype
“类别”。下面,我设置了一个简化的示例来说明我想要完成的任务:
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%timeit df['B'] = df.apply(lambda x: dct.get(x['B']) if x['A'] …
Run Code Online (Sandbox Code Playgroud)