python - Python根据另一个数据框中的列值匹配列名
问题描述
抱歉,如果这是某种重复,我查看了 20 个不同的问题,但没有一个对我有帮助。如果有人可以指出我回答这个问题的问题,我会很乐意删除我的问题。
我有两个数据框,第一个称为 df_full 各种列的长列表,其中一个称为 'Industry' 并具有各种行业的字符串。df_full['Industry'].head()
是:
指数 | 行业 |
---|---|
0 | 服务 |
1 | 服务 |
2 | 贸易 |
3 | 服务 |
4 | 制造业 |
我的第二个数据框称为 df_industry,并具有基于每个行业的分位数。df_industry['profit_sales']
是:
行业 | ||
---|---|---|
金融的 | 0.25 | 0.025616 |
0.50 | 0.219343 | |
0.75 | 0.410408 | |
制造业 | 0.25 | -0.012373 |
0.50 | 0.002032 | |
0.75 | 0.010331 | |
服务 | 0.25 | -0.012660 |
0.50 | 0.003375 | |
0.75 | 0.064102 | |
贸易 | 0.25 | -0.102178 |
0.50 | 0.001715 | |
0.75 | 0.018705 | |
运输 | 0.25 | -0.042755 |
0.50 | -0.042755 | |
0.75 | 0.056487 |
根据列行业的行业,我正在尝试为我的第一个数据框创建一个新的列,分位数为 0.5。
因此我的新输出表应该是这样的,df_full[['Industry','quantile_05']].head()
指数 | 行业 | 分位数_05 |
---|---|---|
0 | 服务 | 0.003375 |
1 | 服务 | 0.003375 |
2 | 贸易 | 0.001715 |
3 | 服务 | 0.003375 |
4 | 制造业 | 0.002032 |
我目前尝试无济于事:
df_full['quantile_05'] = df_full.apply(lambda x: df_industry['profit_sales'][df_full['Industry'][x]][0.5] ,axis=1)
解决方案
看起来你可以做一张地图:
df_full['quantile_05'] = df_full['Industry'].map(df_industry['profit_sales'].unstack()[0.5])
输出:
Industry quantile_05
INDEX
0 Service 0.003375
1 Service 0.003375
2 Trade 0.001715
3 Service 0.003375
4 Manufacturing 0.002032
如果你想要所有三个分位数,你可以merge
按照凯尔的建议做:
df_full.merge(df_industry['profit_sales'].unstack(),
left_on=['Industry'],
right_index=True,
how='left')
输出:
Industry 0.25 0.5 0.75
INDEX
0 Service -0.012660 0.003375 0.064102
1 Service -0.012660 0.003375 0.064102
2 Trade NaN 0.001715 0.018705
3 Service -0.012660 0.003375 0.064102
4 Manufacturing -0.012373 0.002032 0.010331
推荐阅读
- angular - 将多个网站重定向到 C#.net 中的单个域
- android - 如何通过包含依赖项的 gradle 制作 jar
- angular - StaticInjectorError(AppModule)[NbOAuth2AuthStrategy -> InjectionToken Window];NullInjectorError: No provider for InjectionToken Window
- heroku - 如何从 heroku 的 porstgreSQL 备份中只下载特定的表?
- javascript - 将 Tagify javascript 数组转换为字符串
- node.js - iisnode 无法在 Windows 10 家庭版上运行
- python - robotframework rebot --merge 与自定义报告而不是 report.html
- php - 卡夫卡消息重复?
- javascript - 如何在条件语句中添加“如果没有点击”
- python - 读取文件名并用它创建一个列