第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據(jù)另一個數(shù)據(jù)框中的行條件,在一個數(shù)據(jù)框中查找值

根據(jù)另一個數(shù)據(jù)框中的行條件,在一個數(shù)據(jù)框中查找值

Qyouu 2022-06-28 16:39:14
我想向 df1 添加列,該列使用基于 df1 行的條件從 df2 中查找值。例如:df1Name  Date     Score   CountryJohn  1st Jan   5        USJohn  2nd Jan   6        USPhil  1st Jan   4        CanadaPhil  2nd Jan   8        CanadaPhil  3rd Jan   7        Canada如果 Name =John,Date is > 1st of Jan 并且 country 是 = US,我想要一個公式來查找 df2 中另一列的值。所有其他行都相同。
查看完整描述

1 回答

?
神不在的星期二

TA貢獻1963條經(jīng)驗 獲得超6個贊

嘗試這個...


import pandas as pd

import numpy as np


columns = ["Name","Date","Score","Country"]

data=[

    ["John","1st Jan","5","US"],

    ["John","2nd Jan","6","US"],

    ["Phil","1st Jan","4","Canada"],

    ["Phil","2nd Jan","8","Canada"],

    ["Phil","3rd Jan","7","Canada"]

]


columns2 = ["Col1","Col2","Col3","Col4"]

data2 = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4] ]


df = pd.DataFrame(data, columns = columns)

df2 = pd.DataFrame(data2, columns = columns2)

print(df)

print(df2)


df.loc[(df['Name'] == "John")   & 

       (df['Date'] == "1st Jan")&

       (df['Score'] == "5")     &

       (df['Country'] == "US"), 'New'] = df2["Col1"]


name = "Phil"

date = "1st Jan"

score = "4"

country = "Canada"

df.loc[(df['Name'] == name)   & 

       (df['Date'] == date)   &

       (df['Score'] == score) &

       (df['Country'] == country), 'New'] = df2["Col2"]

輸出:


Name     Date Score Country

0  John  1st Jan     5      US

1  John  2nd Jan     6      US

2  Phil  1st Jan     4  Canada

3  Phil  2nd Jan     8  Canada

4  Phil  3rd Jan     7  Canada

Col1  Col2  Col3  Col4

0     1     2     3     4

1     1     2     3     4

2     1     2     3     4

3     1     2     3     4

Name     Date Score Country  New

0  John  1st Jan     5      US  1.0

1  John  2nd Jan     6      US  NaN

2  Phil  1st Jan     4  Canada  2.0

3  Phil  2nd Jan     8  Canada  NaN

4  Phil  3rd Jan     7  Canada  NaN

編輯


您可以通過使用一個函數(shù)df.apply()和一個調(diào)用該函數(shù)的 lambda 來使其更加自動化。


def lambdafunc(row):

    name = row[0]

    date = row[1]

    score = row[2]

    country = row[3]

    df.loc[(df['Name'] == name)   & 

           (df['Date'] == date)   &

           (df['Score'] == score) &

           (df['Country'] == country), 'New'] = df2.loc[df2['Col1'] == name, 'Col4']



df.apply(lambda x: lambdafunc(x), axis = 1)


print(df)


查看完整回答
反對 回復 2022-06-28
  • 1 回答
  • 0 關(guān)注
  • 92 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號