python - 如何在特定条件下将两列合并到第三列
问题描述
我对 Pandas 很陌生,我很难解决这个问题:
我有一个包含医生活动的 DataFrame。
pd0.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 14059 entries, 0 to 4418
Data columns (total 22 columns):
dossier 14059 non-null object
code_praticien 14059 non-null object
nom_praticien 14059 non-null object
code_anesthesiste 13128 non-null object
nom_anesthesiste 13128 non-null object
patient 14059 non-null object
sexe_patient 14059 non-null object
date_naiss_patient 14059 non-null datetime64[ns]
date 14059 non-null datetime64[ns]
heure 13842 non-null float64
ccam_ngap_diag 13852 non-null object
libelle 14059 non-null object
association 7682 non-null float64
modificateur1 11340 non-null object
modificateur2 1262 non-null object
modificateur3 8 non-null float64
modificateur4 0 non-null float64
montant_ccam 13684 non-null float64
montant_ngap 207 non-null float64
depassement 14049 non-null float64
total 13901 non-null float64
praticien 13128 non-null object
dtypes: datetime64[ns](2), float64(8), object(12)
memory usage: 2.8+ MB
两列包含外科医生代码('code_praticien')和麻醉师代码('code_anesthesiste'):
test = pd0[['code_praticien', 'code_anesthesiste']]
test
Out[65]:
code_praticien code_anesthesiste
0 BENY00 MORA01
1 BENY00 MORA01
2 BENY00 MORA01
3 BENY00 MORA01
4 BENY00 MORA01
... ... ...
4414 GAUD00 SAVO01
4415 SAVO01 SAVO01
4416 GAUD00 SAVO01
4417 GAUD00 SAVO01
4418 SAVO01 SAVO01
[14059 rows x 2 columns]
我正在尝试处理“外科医生”是麻醉师的情况(例如:疼痛控制程序)。在这种情况下,我们有 'code_anesthesiste' NaN 和 'code_praticien' 这是麻醉师代码之一。我创建了一个新列“anesthesiste”,当它不为空时将包含“code_anesthesiste”,或者当“code_anesthesiste”为空()和“code_praticien”时包含“code_praticien”([有效code_anesthesiste列表])。
test['anesthesiste'] = test.code_anesthesiste
test.loc[test.code_anesthesiste.isnull() & test.code_praticien.isin(['MORA01', 'SAVO01'])].anesthesiste = pd0.code_praticien
但我不断收到此错误:“ValueError:无法从重复轴重新索引”我用谷歌搜索了“重复轴”,但不明白我的错误在哪里......
我查看了 fillna() 函数,但它似乎不够用,因为我不想在“麻醉剂”列中有外科医生的代码,(有时外科医生在没有麻醉师的情况下工作,然后我有 'code_anesthesiste'NaN ,但“code_praticien”不是麻醉师的代码)。
谢谢你的帮助。
解决方案
你可以在这里使用一个简单的应用:
df = pd.DataFrame({'code_practicien':['BENYY00','BENY00','GAUD00','SAVO01'],'code_anesthesiste':['MORA01','MORA01',np.NaN,'SAVO01']})
df['anethesite']=df.apply(lambda row: row['code_practicien'] if (pd.isnull(row['code_anesthesiste'])&(row['code_practicien'] in ['GAUD00','test'])) else row['code_anesthesiste'],axis=1)
df
替换['GAUD00','test']
为您当前的有效麻醉剂列表
推荐阅读
- http-status-code-403 - 浏览器中的http状态码为200,但http状态检查器中的http状态码为403,为什么?
- sql - 折叠 Hive 中的行并保留非 Null 值
- java - 在纱线模式下使用 Spark 的 Springboot
- kubernetes-helm - 在 Flux 中配置 sops/helm-secrets
- python - 这部分城市引导技能怎么获得?亚马逊sdk python
- python - Python - 'ndarray' 类型的对象不是 JSON 可序列化的
- ruby-on-rails - 当Rails中的字段名称为“日期”时无法订购?
- javascript - 不保留显示每个键的字母(纯javascript)
- neo4j - 如何使这个查询在 neo4j 中更高效?
- javascript - Google Maps Javascript API - 图例最大高度