簡體   English   中英

如何根據行值組合兩個不同長度的熊貓數據框

[英]How to combine two pandas dataframes with different length based on their row values

我有以下兩個熊貓數據框:

數據框 #1:

    user_id       animals    
0         1         'dog'
1         1         'cat'
2         1         'cow'
3         2         'dog'
4         2         'cat'
5         2         'cow'
...

數據框 #2:(column_D 在此任務中不重要)

    location     column_D
0       'CA'            1
1       'MA'            1
2       'AZ'            1
3       'CT'            1
...

我希望基於 #1 和 #2 創建一個新的數據框 #3:

數據框 #3:

    user_id       animals       location
0         1         'dog'           'MA'
1         1         'cat'           'MA'
2         1         'cow'           'MA'
3         2         'dog'           'AZ'
4         2         'cat'           'AZ'
5         2         'cow'           'AZ'
...

數據幀#3 的第一列和第二列與數據幀#1 相同。 對於第三列,我希望根據其 user_id 和數據幀 #2 中的索引分配一個位置。 例如,對於數據幀 #3 中的第 0 行,由於其 user_id = 1,我將檢查數據幀 #2 中索引 = 1 的位置,然后將該位置(在本例中為“MA”)分配給用戶。

我搜索了使用 concat、map、merge 等函數的示例,但找不到與此案例類似的示例。 有沒有辦法完成這個任務?

非常感謝!

嘗試地圖

df["location"] = df1.user_id.map(df2.location)

    user_id animals location
0      1    'dog'   'MA'
1      1    'cat'   'MA'
2      1    'cow'   'MA'
3      2    'dog'   'AZ'
4      2    'cat'   'AZ'
5      2    'cow'   'AZ'

根據您的問題,我不得不假設您要在合並后刪除 column_D。 以下代碼有效。

#Import Pandas
import pandas as pd

#Create dataframes: df1 and df2
df1 = pd.DataFrame({'user_id':{0: 1, 1:1, 2:1, 3:2, 4:2, 5:2}, 'animal':{0:'dog', 1:'cat', 2:'cow', 3:'dog', 4:'cat', 5:'cow'}})
df2 = pd.DataFrame({'location':{0:'CA', 1:'MA', 2:'AZ', 3:'CT'}, 'column_D':{0:1, 1:1, 2:1, 3:1}})
    
#Combine matching items from df2 to df1 by focus on 'user_id'column and drop column_D
df3 = df1.join(df2, on='user_id').drop('column_D', 1)

#Display new dataframe
df3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM