Skip to main content
 首页 » 编程设计

python之使用 pandas to_dict 时排除 NaN

2024年11月24日8shanyou

我正在使用包含一些 NaN 的 pandas DataFrame,例如:

import pandas as pd 
import numpy as np 
 
raw_data={'hostname':{1:'server1',2:'server2',3:'server3',4:'server4'},'nic':{1:'eth1',2:'eth1',3:'eth1',4:'eth1'},'vlan':{1:'100',2:np.nan,3:'200',4:np.nan}} 
 
df=pd.DataFrame(raw_data) 
 
df 
  hostname   nic vlan 
1  server1  eth1  100 
2  server2  eth1  NaN 
3  server3  eth1  200 
4  server4  eth1  NaN 

然后我应用一些过滤并创建一个字典:

my_dict = df.loc[df['hostname'] == 'server2'].drop('hostname', axis=1).to_dict(orient='records') 
 
my_dict 
[{'nic': 'eth1', 'vlan': nan}] 

问题是我想在输出字典中排除任何具有 NaN 值的键,因此 server2 的输出将是:

my_dict 
[{'nic': 'eth1'] 

我在这里找到了一个可能的解决方案:make pandas DataFrame to a dict and dropna

from pandas import compat 
 
def to_dict_dropna(data): 
  return dict((k, v.dropna().to_dict()) for k, v in compat.iteritems(data)) 
 
my_dict=to_dict_dropna(df) 
 
my_dict 
{'nic': {1: 'eth1', 2: 'eth1', 3: 'eth1', 4: 'eth1'}, 'hostname': {1: 'server1', 2: 'server2', 3: 'server3', 4: 'server4'}, 'vlan': {1: '100', 3: '200'}} 

但我不知道如何将此解决方案与我的其他过滤要求和使用 orient='records' 选项相结合。

基本上我需要将上面的 to_dict_dropna 函数包含在我现有的 pandas 选项字符串中。谁能提出解决方案?谢谢

请您参考如下方法:

在你的解决方案之后使用列表理解:

my_dict = (df.loc[df['hostname'] == 'server2'] 
             .drop('hostname', axis=1) 
             .to_dict(orient='records')) 
 
my_dict = [{k:v for k, v in x.items() if v == v } for x in my_dict] 
print (my_dict) 
[{'nic': 'eth1'}]