1 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
一步步:
df1.set_index("MONEY")["Value"]
此代碼將列轉(zhuǎn)換MONEY為Dataframe索引。結(jié)果是:
print(df1)
MONEY
EUR 850
USD 150
DCN 1
df2["Money"].map(df1.set_index("MONEY")["Value"])
此代碼將 的內(nèi)容映射df2到df1。這將返回以下內(nèi)容:
0 150.0
1 NaN
2 850.0
3 NaN
df2現(xiàn)在我們將前一列分配給名為的新列Value。把它們放在一起:
df2["Value"] = df2["Money"].map(df1.set_index("MONEY")["Value"])
df2現(xiàn)在看起來像:
Money Value
0 USD 150.0
1 GBP NaN
2 EUR 850.0
3 CLP NaN
只剩下一件事要做:刪除任何有價(jià)值的行NaN:
df2.dropna(inplace=True)
整個(gè)代碼示例:
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)
輸出:
Money Value
0 USD 150.0
2 EUR 850.0
添加回答
舉報(bào)