[英]how to add value to a new column to a dataframe based on the match of another dataframe?
[英]Python match a column name based on a column value in another dataframe
抱歉,如果這是某種重復,我查看了 20 個不同的問題,但沒有一個對我有幫助。 如果有人可以指出我回答這個問題的問題,我會很樂意刪除我的問題。
我有兩個數據框,第一個稱為 df_full 各種列的長列表,其中一個稱為 'Industry' 並具有各種行業的字符串。 df_full['Industry'].head()
是:
指數 | 行業 |
---|---|
0 | 服務 |
1 | 服務 |
2 | 貿易 |
3 | 服務 |
4 | 制造業 |
我的第二個 dataframe 被稱為 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 |
根據列行業的行業,我正在嘗試為我的第一個 dataframe 創建一個新列,分位數為 0.5。
因此我的新 output 表應該看起來像, 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)
看起來你可以做一個 map:
df_full['quantile_05'] = df_full['Industry'].map(df_industry['profit_sales'].unstack()[0.5])
Output:
Industry quantile_05
INDEX
0 Service 0.003375
1 Service 0.003375
2 Trade 0.001715
3 Service 0.003375
4 Manufacturing 0.002032
如果您想要所有三個分位數,您可以按照 Kyle 的建議進行merge
:
df_full.merge(df_industry['profit_sales'].unstack(),
left_on=['Industry'],
right_index=True,
how='left')
Output:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.