【问题标题】:retrieve values from dataframe using keys in dictionary使用字典中的键从数据框中检索值
【发布时间】:2019-10-23 17:29:10
【问题描述】:

我正在尝试按行业过滤股票代码符号。我找不到使用我创建的字典来引入所有股票代码的方法。如何遍历字典中的键以在其各自列表中引入股票代码?我对python比较陌生,我相信有一个相对简单的方法,我就是找不到。

我的数据框如下所示:

Symbol      industry
TXG         Biotechnology
YI          Medical
PIH         Property Insurers
PIHPP       Property Insurers

除了还有数千行。

# I'm bringing in the values from the column 'industry' and create a dictionary:

industries_var = all_tickers['industry'].values
industries = {industry_name: [] for industry_name in industries_var}

# now I want to iterate through the name of every list in my dictionary 
# and append the matching symbol to the industry name in the dataframe:

for key in industries:
    if all_tickers['industry'].str.contains(key, na=False).any():
        industries.append(all_tickers['Symbol'].values)

我收到错误代码:AttributeError: 'dict' object has no attribute 'append'

我期待一个看起来像这样的字典:

industries = {Biotechnology: ['TXG']
              Medical: ['YI']
              Property Insurers: ['PIH', 'PIHPP']}

我知道您可以在数据框中手动输入每个行业以单独过滤每个列表,但由于有数千行数据,我正在寻找像我上面这样的迭代,只是一个有效的迭代。

谢谢!

【问题讨论】:

  • 这是字典还是熊猫数据框?你引用两个
  • industries[key].append...

标签: python pandas dataframe filter iteration


【解决方案1】:

你需要两个概念来做你想做的事:1) Python defaultdict 2) Pandas/numpy 条件布尔掩码。这是一个使用您的 DataFrame 的工作示例:

import pandas as pd
from collections import defaultdict
all_tickers = pd.DataFrame({'Symbol': ['TXG', 'YI', 'PIH', 'PIHPP'], 'industry': ['Biotechnology', 'Medical', 'Property Insurers', 'Property Insurers']})

industries_var = set(all_tickers['industry'].values)
industries = defaultdict(list)

for k in industries_var:
    industries[k].append(all_tickers[all_tickers.industry == k]['Symbol'].unique())

industries = dict(industries)

还请注意,您不需要像我一样在最后转换回普通字典;普通 dict 和 defaultdict 的操作方式相同,但如果您出于任何原因想要打印到屏幕上,普通 dict 会更好看。

最后,这是一个关于 defaultdicts 的非常全面的讨论: How does collections.defaultdict work?

【讨论】:

    【解决方案2】:

    以前很可能有人问过类似的问题,但我相信这个解决方案可以解决您的问题。

    用每个行业和其中的符号填充字典:

    industries = {}
    for industry in df.industry.unique():
        industries[industry] = df.loc[df.industry == industry].Symbol.unique()
    

    for 循环遍历 DataFrame 中的每个独特行业。然后它将这些行业用作字典的键,并为每个键分配一个数组,其中包含分配给该行业的符号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2018-03-22
      • 2022-11-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多