首页 > 解决方案 > 使用 Pandas 查找表示为字符串的字典的最大值

问题描述

我目前在 Postgres 中有一张表,如下所示:

|----|---------|-----------------|
| id | field_1 | dict_as_string  | 
|----|---------|-----------------|
|  1 | 7293567 | {'1':62,'2':58} |
|----|---------|-----------------|
|  2 | 7924176 | {'1':32,'2':65} |
|----|---------|-----------------|
|  3 | 7492749 | {'1':12,'2':15} |
|----|---------|-----------------|
|  4 | 5829750 | {'1':34,'2':82} |
|----|---------|-----------------|

id 类型文本,field_1 类型 double_precision,dict_as_string 类型文本

我正在将这个 postgres 表读入 pandas 数据框。我要做的是创建一个新列max,它是字典值中的最大值,表示为字符串列dict_as_string。

我将如何尝试。我尝试了以下方法:

df = pd.read_sql_query('select * from "table"', con=connection)
df['dict_as_string'] = df['dict_as_string'].apply(ast.literal_eval)
df['max'] = max(df['dict_as_string'].values())

但这会引发错误

TypeError: 'numpy.ndarray' object is not callable

有没有办法将此表读入熊猫,将 dict_as_string 值从字符串转换为字典,然后使用转换后的字符串的最大值创建一个新列,最终产品看起来像:

|----|---------|-----------------|-----|
| id | field_1 | dict_as_string  | max | 
|----|---------|-----------------|-----|
|  1 | 7293567 | {'1':62,'2':58} |  62 |
|----|---------|-----------------|-----|
|  2 | 7924176 | {'1':32,'2':65} |  65 |
|----|---------|-----------------|-----|
|  3 | 7492749 | {'1':12,'2':15} |  15 |
|----|---------|-----------------|-----|
|  4 | 5829750 | {'1':34,'2':82} |  82 |
|----|---------|-----------------|-----|

标签: pythonpandasdictionary

解决方案


# if you haven't applied ast.literal_eval before:
# df['dict_as_string'] = df['dict_as_string'].apply(ast.literal_eval)

df["max"] = df["dict_as_string"].apply(lambda x: max(x.values()))
print(df)

印刷:

   id  field_1      dict_as_string  max
0   1  7293567  {'1': 62, '2': 58}   62
1   2  7924176  {'1': 32, '2': 65}   65
2   3  7492749  {'1': 12, '2': 15}   15
3   4  5829750  {'1': 34, '2': 82}   82

推荐阅读