gpt4 book ai didi

python - Pandas 从字典映射到 DataFrame

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:16 25 4
gpt4 key购买 nike

我目前正在通过此函数将各种字符串值映射并重命名为 pandas 中的列:

df["fundbenchmark"] = df["name"].map(lambda x: "American Express" if "AXP" in x else "Apple" if "AAPL" in x else "Google" if "GOOG" in x else "")

然而,我将对多个列和许多不同的重命名执行此操作。这是另一个具有相同内容的列,因此将所有公司也添加到那里会是重复的。

df["subclass"] = df["name"].map(lambda x: "American Express" if "AXP" in x else "Apple" if "AAPL" in x else "Google" if "GOOG" in x else "")

因此我想维护一个像这样的字典:

companies = {"AXP": "American Express", "AAPL": "Apple", "GOOG": "Google"}

并在我需要映射公司名称时为所有实例调用它。我怎样才能使 map 匹配 companies 而不是 lambda x


当前数据框:

Name              
"BULL AXP UN X3 VON"
"BEAR AXP UN X3 VON"
"BULL GOOG UN X5 VON"
"BEAR GOOG UN X5 VON"
"BEAR ABC123 X2 CBZ"

期望的输出:

Name                    Fundbenchmark             Subclass
"BULL AXP UN X3 VON" "American Express" "American Express"
"BEAR AXP UN X3 VON" "American Express" "American Express"
"BULL GOOG UN X5 VON" "Google" "Google"
"BEAR GOOG UN X5 VON" "Google" "Google"
"BEAR ABC123 X2 CBZ" "BEAR ABC123 X2 CBZ" "BEAR ABC123 X2 CBZ" #Not in Dictionary

字典:

companies = {"AXP": "American Express", "GOOG": "Google"} 

因此,如果字典中存在缩写,则将该名称写入其他列。

或者,如果字典中没有缩写,则复制整个单元格。

最佳答案

您可以使用 map

Current DataFrame:

Name
"BULL AXP UN X3 VON"
"BEAR AXP UN X3 VON"
"BULL GOOG UN X5 VON"
"BEAR GOOG UN X5 VON"
"BEAR ABC123 X2 CBZ"


companies = {"AXP": "American Express", "GOOG": "Google"}

我们创建一个新列,从您的列中提取代码。

df['Tickers'] = df.Name.str.split(' ').apply(lambda x: x[1])

然后我们使用将您的字典 companies 映射到股票代码来创建一个包含股票代码名称的列:

df['Ticker_Name'] = df['Tickers'].map(companies)

关于python - Pandas 从字典映射到 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30958670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com