熊猫:理解合并是如何运作的

Raf*_*ini 9 python pandas

合并时我做错了什么,我无法理解它是什么.我已经完成以下工作来估计一系列整数值的直方图:

import pandas as pnd
import numpy  as np

series = pnd.Series(np.random.poisson(5, size = 100))
tmp  = {"series" : series, "count" : np.ones(len(series))}
hist = pnd.DataFrame(tmp).groupby("series").sum()
freq = (hist / hist.sum()).rename(columns = {"count" : "freq"})
Run Code Online (Sandbox Code Playgroud)

如果我打印hist,freq这就是我得到的:

> print hist
        count
series       
0           2
1           4
2          13
3          15
4          12
5          16
6          18
7           7
8           8
9           3
10          1
11          1

> print freq 
        freq
series      
0       0.02
1       0.04
2       0.13
3       0.15
4       0.12
5       0.16
6       0.18
7       0.07
8       0.08
9       0.03
10      0.01
11      0.01
Run Code Online (Sandbox Code Playgroud)

他们都被索引,"series"但如果我尝试合并:

> df   = pnd.merge(freq, hist, on = "series")
Run Code Online (Sandbox Code Playgroud)

我得到一个KeyError: 'no item named series'例外.如果我省略,on = "series"我会得到一个IndexError: list index out of range例外.

我不知道我做错了什么.可能是"系列"是一个索引,而不是一列,所以我必须以不同的方式做到这一点?

Ava*_*ris 11

来自docs:

on:要加入的列(名称).必须在左侧和右侧DataFrame对象中找到.如果未传递且left_index和right_index为False,则DataFrame中的列的交集将被推断为连接键

我不知道为什么这不在文档字符串中,但它解释了你的问题.

你可以给left_indexright_index:

In : pnd.merge(freq, hist, right_index=True, left_index=True)
Out:
        freq  count
series
0       0.01      1
1       0.04      4
2       0.14     14
3       0.12     12
4       0.21     21
5       0.14     14
6       0.17     17
7       0.07      7
8       0.05      5
9       0.01      1
10      0.01      1
11      0.03      3
Run Code Online (Sandbox Code Playgroud)

或者您可以将索引设为列并使用on:

In : freq2 = freq.reset_index()

In : hist2 = hist.reset_index()

In : pnd.merge(freq2, hist2, on='series')
Out:
    series  freq  count
0        0  0.01      1
1        1  0.04      4
2        2  0.14     14
3        3  0.12     12
4        4  0.21     21
5        5  0.14     14
6        6  0.17     17
7        7  0.07      7
8        8  0.05      5
9        9  0.01      1
10      10  0.01      1
11      11  0.03      3
Run Code Online (Sandbox Code Playgroud)

或者更简单地说,DataFramejoin一种方法可以完全按照你的意愿行事:

In : freq.join(hist)
Out:
        freq  count
series
0       0.01      1
1       0.04      4
2       0.14     14
3       0.12     12
4       0.21     21
5       0.14     14
6       0.17     17
7       0.07      7
8       0.05      5
9       0.01      1
10      0.01      1
11      0.03      3
Run Code Online (Sandbox Code Playgroud)