Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

python pandas: pivot_table silently drops indices with nans

Is there an option not to drop the indices with NaN in them? I think silently dropping these rows from the pivot will at some point cause someone serious pain.

import pandas
import numpy

a = [['a', 'b', 12, 12, 12], ['a', numpy.nan, 12.3, 233., 12], ['b', 'a', 123.23, 123, 1], ['a', 'b', 1, 1, 1.]]

df = pandas.DataFrame(a, columns=['a', 'b', 'c', 'd', 'e'])

df_pivot = df.pivot_table(index=['a', 'b'], values=['c', 'd', 'e'], aggfunc=sum)
print(df)
print(df_pivot)

Output:

   a    b       c    d   e
0  a    b   12.00   12  12
1  a  NaN   12.30  233  12
2  b    a  123.23  123   1
3  a    b    1.00    1   1
          c    d   e
a b                 
a b   13.00   13  13
b a  123.23  123   1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is currently not supported, see this issue for the enhancement: https://github.com/pydata/pandas/issues/3729.

Workaround to fill the index with a dummy, pivot, and replace

In [28]: df = df.reset_index()

In [29]: df['b'] = df['b'].fillna('dummy')

In [30]: df['dummy'] = np.nan

In [31]: df
Out[31]: 
   a      b       c    d   e  dummy
0  a      b   12.00   12  12    NaN
1  a  dummy   12.30  233  12    NaN
2  b      a  123.23  123   1    NaN
3  a      b    1.00    1   1    NaN

In [32]: df.pivot_table(index=['a', 'b'], values=['c', 'd', 'e'], aggfunc=sum)
Out[32]: 
              c    d   e
a b                     
a b       13.00   13  13
  dummy   12.30  233  12
b a      123.23  123   1

In [33]: df.pivot_table(index=['a', 'b'], values=['c', 'd', 'e'], aggfunc=sum).reset_index().replace('dummy',np.nan).set_index(['a','b'])
Out[33]: 
            c    d   e
a b                   
a b     13.00   13  13
  NaN   12.30  233  12
b a    123.23  123   1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...