Pandas DataFrame.add() - 忽略缺少的列

时间:2018-02-28 22:06:21

标签: python pandas dataframe

我有以下两个DataFrame:

>>> history
              above below
asn   country
12345 US          5     4
      MX          6     3
54321 MX          4     5
>>> current
              above below
asn   country
12345 MX          1     0
54321 MX          0     1
      US          1     0

我保持"以上"的运行计数。和"以下" history DataFrame中的值如下:

>>> history = history.add(current, fill_value=0)
>>> history
               above  below
asn   country              
12345 MX         7.0    3.0
      US         5.0    4.0
54321 MX         4.0    6.0
      US         1.0    0.0

只要current DataFrame中没有额外的列,这就有效。但是当我添加一个额外的列时:

>>> current
              above below cruft
asn   country
12345 MX          1     0   999
54321 MX          0     1   999
      US          1     0   999

我得到以下内容:

>>> history = history.add(current, fill_value=0)
>>> history
               above  below cruft
asn   country              
12345 MX         7.0    3.0 999.0
      US         5.0    4.0   NaN
54321 MX         4.0    6.0 999.0
      US         1.0    0.0 999.0

我希望忽略这个额外的列,因为它在两个DataFrame中都不存在。所需的输出只是:

>>> history
               above  below
asn   country              
12345 MX         7.0    3.0
      US         5.0    4.0
54321 MX         4.0    6.0
      US         1.0    0.0

3 个答案:

答案 0 :(得分:7)

sshfs

答案 1 :(得分:7)

嗯,一种新的方式

composer update

答案 2 :(得分:4)

您可以先在最终输出中指定所需的列列表:

cols_to_return = ["above", "below"]
history = history[cols_to_return].add(current[cols_to_return], fill_value=0)

通过事先指定列确实可以帮助您跟踪您正在做的事情并调试未来的问题。