简体   繁体   中英

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?

First, the I import the following text file:

 ['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']]

Where the first column is the animal, the second is its x location in a field, the third column is its y location, and the fourth column is its z location. I would like to find the minimum/maximum Z values as well as the number of each type of animal and save all of this information in a new dictionary. So far I have tried this:

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)

However, the minimum/maximum values I am getting for each animal are the overall mins/maxs for the whole dictionary and the number of animals is the total number of animals in the dictionary. Like so:

{'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}}

Any idea how I could fix my code to give me the min/max and number of each animal from my text file? Thanks!!

df['z'] returns the values of all z values, not just in the rows where animal == 'k' . You need to filter the dataframe.

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

Although you're asking for a dictionary, I'll provide a suggestion that takes advantage of Pandas DataFrame (since you already have a DataFrame). You can accomplished this in a vectorized fashion using the Pandas groupby and the Groupby min and max functions.

Here's an example:

>>> 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}}

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