olivier dadoun
olivier dadoun

Reputation: 743

NaN columns pandas turning into empty row when using pivot_table

I use read_csv to fill a pandas. In this pandas I have a full NaN empty columns and this turns into a problem when I use pivot_table. Here my situation:

d= {'dates': ['01/01/20','01/02/20','01/03/20'], 'country':['Fra','Fra','Fra'], 'val': [np.nan,np.nan,np.nan]} 
df = pd.DataFrame(data=d)
piv=df.pivot_table(index='country',values='val',columns='dates')
print(piv)
Empty DataFrame
Columns: []
Index: []

I would like to have this :

dates    01/01/20  01/02/20  01/03/20
country                              
Fra             NaN         NaN         NaN

Upvotes: 0

Views: 1147

Answers (2)

Roy2012
Roy2012

Reputation: 12503

Just use the dropna argument of pivot:

df.pivot_table(index='country',columns='dates', values='val', dropna = False)

The output is:

dates    01/01/20  01/02/20  01/03/20
country                              
Fra           NaN       NaN       NaN

Upvotes: 1

sushanth
sushanth

Reputation: 8302

from docs, set dropna = False DataFrame.pivot_table

piv = df.pivot_table(index='country',values='val',columns='dates', dropna=False)

dates    01/01/20  01/02/20  01/03/20
country                              
Fra           NaN       NaN       NaN

Upvotes: 3

Related Questions