熊猫根据来自另一列的值来映射列数据,并使用if来确定要使用哪个字典 - python

我有以下数据框:

df = pd.DataFrame([['Person1', 'CT', 2017],
               ['Person2', 'FL', 2017],
               ['Person3', 'TX', 2017],
              ['Person1', 'TX', 2016]], columns=['Name', 'State', 'Year'])

还有下面的两个映射表:

state_map = {'CT': 'Connecticut', 'FL': 'Florida', 'TX':'Texas'}
state_map2 = {'CT': 'ABC-CT', 'FL': 'BBC-Florida', 'TX':'CDA-TX'}

数据如下所示:

    Name    State   Year
0   Person1   CT    2017
1   Person2   FL    2017
2   Person3   TX    2017
3   Person1   TX    2016

我想找到一种添加新列的方法,该列使用if条件确定是否使用从state_map或state_map2映射的值映射的值。因此,如果df [df ['Name'] =='Person1'],则使用state_map,否则使用state_map2。

最终输出应如下所示:

    Name    State   Year   New_State_Name
0   Person1   CT    2017   Connecticut
1   Person2   FL    2017   BBC-Florida
2   Person3   TX    2017   CDA-TX
3   Person1   TX    2016   Texas

我尝试了以下代码,但是没有用。

df['New_State_Name'] = [state_map[x] if df[df['Name'] == 'Person1'] else 
state_map2[x] for x in df['State']]

我收到一个错误消息:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, 
a.bool(), a.item(), a.any() or a.all().

参考方案

使用np.where

df['New_State_Name'] = np.where(df['Name']=='Person1',df['State'].map(state_map),df['State'].map(state_map2))

输出:

      Name State  Year New_State_Name
0  Person1    CT  2017    Connecticut
1  Person2    FL  2017    BBC-Florida
2  Person3    TX  2017         CDA-TX
3  Person1    TX  2016          Texas

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…

如何用'-'解析字符串到节点js本地脚本? - python

我正在使用本地节点js脚本来处理字符串。我陷入了将'-'字符串解析为本地节点js脚本的问题。render.js:#! /usr/bin/env -S node -r esm let argv = require('yargs') .usage('$0 [string]') .argv; console.log(argv…