我在合并方面做错了,我不明白它是什么。我已完成以下操作来估计一系列整数值的直方图:
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"})
如果我打印 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
它们都由 "series"
索引,但如果我尝试合并:
> df = pnd.merge(freq, hist, on = "series")
我收到一个 KeyError: 'no item named series'
异常。如果我省略 on = "series"
,我会得到一个 IndexError: list index out of range
异常。
我不明白我做错了什么。可能是“系列”是索引而不是列,所以我必须以不同的方式来做?
最佳答案
来自 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
我不知道为什么这不在文档字符串中,但它解释了你的问题。
你可以给 left_index
和 right_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
关于python - Pandas :难以理解合并的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10145224/