【问题标题】:How do I find the minimum/maximum value for each key in a dictionary? And how do I find the number of values for each key?如何找到字典中每个键的最小值/最大值?以及如何找到每个键的值的数量?
【发布时间】:2020-03-11 22:45:18
【问题描述】:

首先,我导入以下文本文件:

 ['butterfly' '2' '2' '3']
 ['butterfly' '3' '3' '3']
 ['dragonfly' '4' '1' '1']
 ['dragonfly' '5' '2' '1']
 ['dragonfly' '6' '3' '1']
 ['cat' '4' '4' '2']
 ['cat' '5' '5' '2']
 ['cat' '6' '6' '2']
 ['cat' '7' '8' '3']
 ['elephant' '8' '9' '3']
 ['elephant' '9' '10' '4']
 ['elephant' '10' '10' '4']
 ['camel' '10' '11' '5']
 ['camel' '11' '6' '5']
 ['camel' '12' '5' '6']
 ['camel' '12' '3' '6']
 ['bear' '13' '13' '7']
 ['bear' '5' '15' '7']
 ['bear' '4' '10' '5']
 ['bear' '6' '9' '2']
 ['bear' '15' '13' '1']
 ['dog' '1' '3' '9']
 ['dog' '2' '12' '8']
 ['dog' '3' '10' '1']
 ['dog' '4' '8' '1']]

其中第一列是动物,第二列是它在字段中的 x 位置,第三列是它的 y 位置,第四列是它的 z 位置。 我想找到最小/最大 Z 值以及每种动物的数量,并将所有这些信息保存在新字典中。到目前为止,我已经尝试过:

df = pd.read_csv('ALL_ANIMALS.txt',
                 delim_whitespace=True,
                 names={'animal':str,'x':int,'y':int,'z':int}) #load in file
Animal_Data = {}

Animal_Data['Max_Depths'] = {k : max(df['z']) for k in df['animal']} #find max value (depth) for each key (animal)
Animal_Data['Min_Depths'] = {k : min(df['z']) for k in df['animal']} #find min value (depth) for each key (animal)

Animal_Data['number_of_each_animal'] = {k : len(df['z']) for k in df['animal']} #find number of each animal

print(Animal_Data)

但是,我为每只动物获得的最小/最大值是整个字典的总最小值/最大值,而动物的数量是字典中动物的总数。像这样:

{'Max_Depths': {'cat': 9, 'elephant': 9, 'camel': 9, 'bear': 9, 'dog': 9}, 'Min_Depths': {'cat': 1, 'elephant': 1, 'camel': 1, 'bear': 1, 'dog': 1}, 'number_of_each_animal': {'cat': 20, 'elephant': 20, 'camel': 20, 'bear': 20, 'dog': 20}}

知道如何修复我的代码以从我的文本文件中为我提供每只动物的最小/最大和数量吗?谢谢!!

【问题讨论】:

  • 您需要将df['z'] 限制在df['animal'] == k 所在的行
  • 这里有使用字典的理由吗?如果您已经拥有 pandas,我不确定您为什么不坚持使用数据框(一个认真的问题!)。

标签: python pandas dictionary minimum dictionary-comprehension


【解决方案1】:

df['z'] 返回 所有 z 值的值,而不仅仅是在 animal == 'k' 所在的行中。您需要过滤数据框。

Animal_Data['Max_Depths'] = {k: max(df.loc[df.animal == k, 'z']) for k in df['animal'].unique()}

【讨论】:

    【解决方案2】:

    虽然您要的是字典,但我会提供一个利用 Pandas DataFrame 的建议(因为您已经有一个 DataFrame)。您可以使用 Pandas groupby 和 Groupby minmax 函数以矢量化方式完成此操作。

    这是一个例子:

    >>> df
           animal   x   y  z
    0   butterfly   2   2  3
    1   butterfly   3   3  3
    2   dragonfly   4   1  1
    3   dragonfly   5   2  1
    4   dragonfly   6   3  1
    5         cat   4   4  2
    6         cat   5   5  2
    7         cat   6   6  2
    8         cat   7   8  3
    9    elephant   8   9  3
    10   elephant   9  10  4
    11   elephant  10  10  4
    12      camel  10  11  5
    13      camel  11   6  5
    14      camel  12   5  6
    15      camel  12   3  6
    16       bear  13  13  7
    17       bear   5  15  7
    18       bear   4  10  5
    19       bear   6   9  2
    20       bear  15  13  1
    21        dog   1   3  9
    22        dog   2  12  8
    23        dog   3  10  1
    24        dog   4   8  1
    >>> min_series = df.groupby('animal').z.min()
    >>> min_series.rename('Min_Depths', inplace=True)
    animal
    bear         1
    butterfly    3
    camel        5
    cat          2
    dog          1
    dragonfly    1
    elephant     3
    Name: Min_Depths, dtype: int64
    >>> max_series = df.groupby('animal').z.max()
    >>> max_series.rename('Max_Depths', inplace=True)
    animal
    bear         7
    butterfly    3
    camel        6
    cat          3
    dog          9
    dragonfly    1
    elephant     4
    Name: Max_Depths, dtype: int64
    >>> pd.concat([min_series, max_series], axis=1)
               Min_Depths  Max_Depths
    animal
    bear                1           7
    butterfly           3           3
    camel               5           6
    cat                 2           3
    dog                 1           9
    dragonfly           1           1
    elephant            3           4
    >>> animal_data_df = pd.concat([min_series, max_series], axis=1)
    >>> animal_data_df.to_dict()
    {'Min_Depths': {'bear': 1, 'butterfly': 3, 'camel': 5, 'cat': 2, 'dog': 1, 'dragonfly': 1, 'elephant': 3}, 'Max_Depths': {'bear': 7, 'butterfly': 3, 'came
    l': 6, 'cat': 3, 'dog': 9, 'dragonfly': 1, 'elephant': 4}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 2013-10-24
      • 2017-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2011-07-16
      相关资源
      最近更新 更多