Python Pandas : combine 2 dataframes, 一帧的列作为最终结果的索引

标签 python pandas

数据帧 df1:

+--------+------+--------+
| userId | isbn | rating |
+--------+------+--------+
|      1 | 0001 |      3 |
|      2 | 0002 |      4 |
|      2 | 0003 |      5 |
+--------+------+--------+

数据帧 df2:

+------+-------+
| isbn | title |
+------+-------+
| 0001 | aaa   |
| 0002 | bbb   |
| 0003 | ccc   |
+------+-------+

我可以将它们合并到:

+-----+-----+-----+
|     |  1  |  2  |
+-----+-----+-----+
| aaa | 3   | NAN |
| bbb | NAN | 4   |
| ccc | NAN | 5   |
+-----+-----+-----+

其中列是userId,索引是标题isbn 在合并后被删除。

谢谢。

最佳答案

一旦你merge这些框架,您可以使用pivot_table :

In [11]: merged = df.merge(df2)

In [12]: merged
Out[12]:
   userId  isbn  rating title
0       1     1       3   aaa
1       2     2       4   bbb
2       2     3       5   ccc

In [13]: merged.pivot_table('rating', 'title', 'userId')
Out[13]:
userId   1   2
title
aaa      3 NaN
bbb    NaN   4
ccc    NaN   5

关于Python Pandas : combine 2 dataframes, 一帧的列作为最终结果的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22056244/

相关文章:

python - 在时间轴上绘制离散组计数

python - 为什么我在 matplotlib 中的绘图没有显示轴

Python: "if i.find(' a') ['id' ] is not None :"returns TypeError ' NoneType' 对象不可下标,但 print() 返回一个值

python - 使用 feedparser 从博客中获取每个独特的项目。检查 for 循环中的列表成员身份不起作用

python - 如何向 pandas 数据框添加二级索引

python - 如何使用 dask 读取 csv 并处理行?

python - Pandas:等效于 Excel sumifs

python - Web 从表格中抓取数据

python - 了解 scipy.ndimage.map_coordinates 上的输入和输出

python - Pandas :根据另一个数据框中的行值计数进行转换