Home > OS >  Pandas remove NaN and move all value on the same line
Pandas remove NaN and move all value on the same line

Time:08-11

I have a simple list that want to convert it to excel using pandas. I googled about how to remove NaN, but they all talk about remove either whole row or column. Is there a way to put all the value on the same line?

list = [{'cisco': 15}, {'developer': 15}, {'root': 15}]
df = pd.DataFrame(list)

The output is like this cisco developer root 0 15.0 NaN NaN 1 NaN 15.0 NaN 2 NaN NaN 15.0

But I would like to have it look like this cisco developer root 0 15.0 15.0 15.0

CodePudding user response:

You need change format, you can use:

l = [{'cisco': 15}, {'developer': 15}, {'root': 15}]

print ({k: v for x in l for k, v in x.items()})
{'cisco': 15, 'developer': 15, 'root': 15}

df = pd.DataFrame([{k: v for x in l for k, v in x.items()}])
#if one element dicts
df = pd.DataFrame([{list(x.keys())[0]: list(x.values())[0] for x in l}])

print (df)
   cisco  developer  root
0     15         15    15

If already missing values in DataFrame:

df = pd.DataFrame(l)

df = df.stack().droplevel(0).to_frame().T
print (df)
   cisco  developer  root
0   15.0       15.0  15.0

CodePudding user response:

You should consider the values as a list, Below format works

df_list = {'cisco': [15], 'developer': [15], 'root': [15]}

df = pd.DataFrame(df_list)

CodePudding user response:

Python has a tool to merge dictionaries: ChainMap:

from collections import ChainMap

lst = [{'cisco': 15}, {'developer': 15}, {'root': 15}]

df = pd.DataFrame([ChainMap(*lst)])

Output:

   cisco  developer  root
0     15         15    15
  • Related