簡體   English   中英

Pandas:在 2 個數據幀之間按每一行比較一列的值,並根據匹配替換另一列中的值

[英]Pandas: Compare value for a column by each row between 2 dataframes and replace value in another column based on the match

我有2個數據框:

DF1:

    SICCode Industry Title
0   4941    AGRICULTURAL PRODUCTION-CROPS
1   7374    AGRICULTURAL PROD-LIVESTOCK & ANIMAL SPECIALTIES
2   5065    AGRICULTURAL SERVICES
3   4941    FORESTRY
4   5122    FISHING, HUNTING AND TRAPPING

DF2:

    SICCode Sector
0   4941    Buseq
1   7374    utils
2   5065    shops
3   4941    utils
4   5122    Buseq

DF1 為主; 我想在 DF2 的 SIC 代碼中檢查 DF1 中的每個 SIC 代碼,如果存在,我想用行業標題下的相應值替換部門列中的值。 例如,對於 DF1 中的 4941,它應該反對 DF2 中 SIC 代碼中的所有值,並將 Buseq 和 utils 替換為“農業生產作物”。

我嘗試了 .map、.isin、if-else 等,但無法繼續前進。 請問有什么建議嗎?

請注意,在您的主 df SICCode 中不是主鍵,在示例中,您的節目中有兩行具有相同的代碼,這可能是一個問題,請注意(我在解決方案中任意編輯了林業的 SICCode,但如果您不使用 Buseq 和 utils 將被 Forestry 取代)

我看到您的問題的 2 個解決方案:

  • 僅使用熊貓:
import pandas as pd

df1 = {'SICCode':[4941,7374,5065,4944,5122], \
       'Industry_Title' :['AGRICULTURAL PRODUCTION-CROPS',\
                          'AGRICULTURAL PROD-LIVESTOCK & ANIMAL SPECIALTIES',\
                          'AGRICULTURAL SERVICES','FORESTRY',\
                          'FISHING  HUNTING AND TRAPPING']}
df2 =  {  'SICCode':[4941,7374,5065,4941,5122], 'Sector': ['Buseq','utils','shops','utils','Buseq']}

df1 = pd.DataFrame(df1)
df2 = pd.DataFrame(df2)

for index in df2.index:

    to_replace = df1[df1['SICCode'] == df2.loc[index,'SICCode']]
    for i in to_replace['Industry_Title'].index:
        df2.loc[index,'Sector'] = to_replace['Industry_Title'][i]
  • 使用 sqlite3:
import pandas as pd
import sqlite3 as sql

df1 = {'SICCode':[4941,7374,5065,4944,5122], \
       'Industry_Title' :['AGRICULTURAL PRODUCTION-CROPS',\
                          'AGRICULTURAL PROD-LIVESTOCK & ANIMAL SPECIALTIES',\
                          'AGRICULTURAL SERVICES','FORESTRY',\
                          'FISHING  HUNTING AND TRAPPING']}
df2 =  {  'SICCode':[4941,7374,5065,4941,5122], 'Sector': ['Buseq','utils','shops','utils','Buseq']}

df1 = pd.DataFrame(df1)
df2 = pd.DataFrame(df2)  

conn = sql.connect('test_database.db')
c = conn.cursor()

c.execute('CREATE TABLE IF NOT EXISTS df1 (SICCode Integer, Industry_Title Text)')
c.execute('CREATE TABLE IF NOT EXISTS df2 (SICCode Integer, Sector Text)')


df1.to_sql('df1', conn, if_exists='replace', index = False)
df2.to_sql('df2', conn, if_exists='replace', index = False)
# create the database witht the table

to_replace = c.execute("""
          Select df2.SICCode,Industry_Title From
          df1 Join df2 On df1.SICCode=df2.SICCode
          """).fetchall()
# select rows with same SICCode in df1 and df2

for x in to_replace:
    c.execute("""
              Update df2 Set Sector = '{}'
              Where SICCode = {}
              """.format(x[1],x[0]))
    #updates the row of df2

conn.commit()
conn.close()

也許有點粗糙,但有效。

df2 = df2.merge(df1, on="SICode", how="left")
df2.drop(['Sector'], inplace=True, axis=1)

暫無
暫無

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

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