Reputation: 205
samp dataframe
v1 v2 v3 v4 v5 v6
index
0 -2 -2 -2 NaN -2 -2
1 -2 -2 -2 NaN -2 -2
2 -2 -2 -2 NaN -2 -2
3 -2 -2 -2 -2 -2 -2
4 -2 -2 -2 NaN -2 -2
Am trying to change dataframe to dictionary and i want to ignore 'nan' field in json documents
What am trying:
import pandas as pd
pd.DataFrame((samp.to_dict('index')).items())
Desired output:
index values
0 {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}
1 {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}
2 {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}
3 {'v1':'-2', 'v2':'-2','v3':'-2','v4':'-2','v5':'-2','v6':'-2'}
4 {'v1':'-2', 'v2':'-2','v3':'-2','v5':'-2','v6':'-2'}
Upvotes: 1
Views: 3747
Reputation: 323326
Do it with apply
df.apply(lambda x : x.dropna().to_dict(),axis=1)
Out[362]:
index
0 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2....
1 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2....
2 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2....
3 {'v4': -2.0, 'v3': -2.0, 'v5': -2.0, 'v2': -2....
4 {'v3': -2.0, 'v5': -2.0, 'v6': -2.0, 'v1': -2....
dtype: object
Upvotes: 9