python - 使用 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 |
|----|---------|-----------------|-----|
解决方案
# 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
推荐阅读
- javascript - 基于类名的动画元素(许多项目共享同一个类)
- r - 找出独特关卡之间的差异
- python - ValueError:无法将字符串转换为浮点数---如何将字符串列表转换为 numpy 数组类型浮点数?
- python-3.x - 截距强制为零和斜率值不确定性的线性回归
- php - 如何区分段落单词和数组PHP
- swift - UITextChecker、Swift 的单词学习——不工作
- php - Laravel Eloquent 连接表关系
- eclipse - xquery (.xq) 文件编辑器,在 eclipse photon 中具有语法高亮显示
- java - 使用@Async 注解时的线程安全
- go - 如何使用 go lang 下载和保存整个网页