简体   繁体   中英

How can I filter an pandas dataframe with another Smaller pandas dataframe

I have 2 Data frames the first looks like this

df1:

    MONEY    Value
0    EUR      850
1    USD      750
2    CLP        1
3    DCN        1

df2:

      Money
0      USD
1      USD
2      USD
3      USD
4      EGP
...    ...
25984  USD
25985  DCN
25986  USD
25987  CLP
25988  USD

I want to remove the "Money" values of df2 that are not present in df1. and add any column of the values of the "Value" column in df1

  Money    Value
0      USD      720
1      USD      720
2      USD      720
3      USD      720
...    ...
25984  USD      720
25985  DCN        1
25986  USD      720
25987  CLP        1
25000  USD      720

Step by step:

df1.set_index("MONEY")["Value"]

This code transforms the column MONEY into the Dataframe index. Which results in:

    print(df1)

    MONEY
    EUR    850
    USD    150
    DCN      1

df2["Money"].map(df1.set_index("MONEY")["Value"])

This code maps the content of df2 to df1 . This returns the following:

    0    150.0
    1      NaN
    2    850.0
    3      NaN

  1. Now we assign the previous column to a new column in df2 called Value . Putting it all together:
df2["Value"] = df2["Money"].map(df1.set_index("MONEY")["Value"])

df2 now looks like:

     Money  Value
    0   USD  150.0
    1   GBP    NaN
    2   EUR  850.0
    3   CLP    NaN

  1. Only one thing is left to do: Delete any rows that have NaN value:
df2.dropna(inplace=True)

Entire code sample:

import pandas as pd

# Create df1
x_1 = ["EUR", 850], ["USD", 150], ["DCN", 1]
df1 = pd.DataFrame(x_1, columns=["MONEY", "Value"])

# Create d2
x_2 = "USD", "GBP", "EUR", "CLP"
df2 = pd.DataFrame(x_2, columns=["Money"])

# Create new column in df2 called 'Value'
df2["Value"] = df2["Money"].map(df1.set_index("MONEY")["Value"])
# Drops any rows that have 'NaN' in column 'Value'
df2.dropna(inplace=True)
print(df2)

Outputs:

Money  Value
0   USD  150.0
2   EUR  850.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM