试图了解pandas合并的工作方式,特别是加入

时间:2017-08-14 20:57:25

标签: python pandas

我在一个更大的数据框架中遇到了一个令人困惑的结果,制作了一个可以捕捉到让我困惑的一些玩具:

import pandas as pd
big_index = [123, 124, 125, 126, 127, 128, 129, 130]
big_dat = {'year': pd.Series([2000, 2000, 2000, 2001, 2002, 2002, 2002, 2004], index=big_index),
      'other': pd.Series(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], index=big_index)}
big_df = pd.DataFrame(big_dat)

year_index = [2003, 2000, 2001, 2002]
year_dat = {'a': pd.Series([1, 2, 3, 4], index=year_index),
        'b': pd.Series([5, 6, 7, 8], index=year_index)}
year_df = pd.DataFrame(year_dat)

左,内部合并按照我的预期工作,但是右边和外边产生奇怪的结果:

merged_right = pd.merge(
    big_df,
    year_df,
    how='right',
    left_on='year',
    right_index=True
    )
merged_right
    other  year  a  b
123     a  2000  2  6
124     b  2000  2  6
125     c  2000  2  6
126     d  2001  3  7
127     e  2002  4  8
128     f  2002  4  8
129     g  2002  4  8
130   NaN  2003  1  5

merged_outer = pd.merge(
    big_df,
    year_df,
    how='outer',
    left_on='year',
    right_index=True
    )
merged_outer
    other  year    a    b
123     a  2000  2.0  6.0
124     b  2000  2.0  6.0
125     c  2000  2.0  6.0
126     d  2001  3.0  7.0
127     e  2002  4.0  8.0
128     f  2002  4.0  8.0
129     g  2002  4.0  8.0
130     h  2004  NaN  NaN
130   NaN  2003  1.0  5.0

在这两种情况下,索引130与2003年的进入相关联,没有明显的原因。我知道没有“好”的方法来处理这个,因为我假设索引本身不能有NaN。我曾经预料到这会抛出一个错误,而不是返回那个不正确的最后一列。我可能误解了熊猫正在做什么。有关资源的提示,以找出出现问题的原因,与表示如何正确执行此操作的代码一样受到赞赏。

0 个答案:

没有答案