簡體   English   中英

熊貓:理解合並是如何運作的

[英]Pandas: trouble understanding how merge works

合並時我做錯了什么,我無法理解它是什么。 我已經完成以下工作來估計一系列整數值的直方圖:

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異常。

我不知道我做錯了什么。 可能是“系列”是一個索引,而不是一列,所以我必須以不同的方式做到這一點?

來自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

或者你可以讓你的索引中的列和使用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具有join方法,它可以完全滿足您的需求:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM