Pandas:无法理解merge是如何工作的

2024-05-16 21:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我对merge做了些错事,我不明白它是什么。我已经做了以下工作来估计一系列整数值的直方图:

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"})

如果我打印histfreq这就是我得到的:

> 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

它们都由"series"索引,但是如果我尝试合并:

> df   = pnd.merge(freq, hist, on = "series")

我得到一个KeyError: 'no item named series'异常。如果省略on = "series",则会得到IndexError: list index out of range异常。

我不明白我做错了什么。可能“series”是一个索引,而不是一个列,所以我必须用不同的方法来做?


Tags: importonascountnp整数mergehist
1条回答
网友
1楼 · 发布于 2024-05-16 21:10:12

来自docs

on: Columns (names) to join on. Must be found in both the left and right DataFrame objects. If not passed and left_index and right_index are False, the intersection of the columns in the DataFrames will be inferred to be the join keys

我不知道为什么这不在docstring中,但它解释了你的问题。

您可以给出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

或者可以将索引设为列并使用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

或者,更简单地说,DataFrame有一个^{}方法,它可以完全满足您的需要:

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

相关问题 更多 >