【发布时间】:2022-12-12 08:32:11
【问题描述】:
首先,如果标题难以理解,请见谅。
目标:
我正在尝试按 source, type 列分组,按结果为每个组添加 min,max 列
,然后将相关的 target 列添加到 min 和 max 列(在值的前面)。
我不知道如何以这种格式获得 Pandas 结果:
| source | type | min | max |
|---|---|---|---|
| Person1 | bow | Person 2: 0.001 | Person 3: 0.05 |
我有一个字典列表如下:
`[{'source': 'Person1', 'target': 'Person2', 'type': 'bow', 'similarity': 0.636}, {'source': 'Person1', 'target': 'Person2', 'type': 'bigram', 'similarity': 0.040}, {'source': 'Person1', 'target': 'Person2', 'type': 'tfidf', 'similarity': 0.433}, {'source': 'Person1', 'target': 'Person3', 'type': 'bow', 'similarity': 0.699}, {'source': 'Person1', 'target': 'Person3', 'type': 'bigram', 'similarity': 0.171}, {'source': 'Person1', 'target': 'Person3', 'type': 'tfidf', 'similarity': 0.522}]`
在这个表中看起来像:
| source | target | type | similarity |
|---|---|---|---|
| Person1 | Person2 | bow | 0.636 |
| Person1 | Person2 | bigram | 0.040 |
| Person1 | Person2 | tfidf | 0.433 |
| Person1 | Person3 | bow | 0.699 |
| Person1 | Person3 | bigram | 0.171 |
| Person1 | Person3 | tfidf | 0.522 |
对于分组依据,最小/最大我使用以下内容:
df = df.groupby(['source','type']).similarity.agg(['min','max'])
结果为:
| source | type | min | max |
|---|---|---|---|
| Person1 | bow | 0.636 | 0.699 |
| Person1 | bigram | 0.040 | 0.171 |
| Person1 | tfidf | 0.433 | 0.522 |
到目前为止一切都很好,但是如何将输出转换为以下结构:
[资源]:资源;[类型]: 类型;[分钟]:目标:最小值(相似度);[最大限度]:目标:最大(相似度)
| source | type | min | max |
|---|---|---|---|
| Person1 | bow | Person2: 0.636 | Person3: 0.699 |
| Person1 | bigram | Person2: 0.040 | Person3: 0.171 |
| Person1 | tfidf | Person3: 0.433 | Person3: 0.522 |
我是否应该使用 .loc 来查找最小/最大值所在的行,然后以某种方式将它们添加到结果中?
【问题讨论】:
标签: pandas