从批注中删除nan

2024-04-23 23:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

如何删除y=nanlistdictionary中的记录,如下所示

[{'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2018-Q3', 'y': 169.80000000000001, 'text': '169.8', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2018-Q4', 'y': 53.829999999999998, 'text': '53.83', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q1', 'y': 63.420000000000002, 'text': '63.42', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q2', 'y': 42.369999999999997, 'text': '42.37', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q3', 'y': nan, 'text': 'nan', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q4', 'y': nan, 'text': 'nan', 'showarrow': False}]

Tags: textfalseautodictionary记录nanlistbottom
3条回答

你的问题形式不太好,但我会做一些假设并尽力提供帮助。
试试这个:

import numpy as np
nan = np.nan
dict_list = [{'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2018-Q3', 'y': 169.80000000000001, 'text': '169.8', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2018-Q4', 'y': 53.829999999999998, 'text': '53.83', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q1', 'y': 63.420000000000002, 'text': '63.42', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q2', 'y': 42.369999999999997, 'text': '42.37', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q3', 'y': nan, 'text': 'nan', 'showarrow': False}, {'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2019-Q4', 'y': nan, 'text': 'nan', 'showarrow': False}]
filtered_dict_list = [x for x in dict_list if not np.isnan(x['y'])]

这是一个简单的列表理解过滤,谷歌它…
祝你好运


假设:

  • nan应该是numpy.nan
  • 你所说的“删除”是指“获取一个新的词典列表,其中不包括不需要的词典”

下面的方法奏效了

新记录2=[] 对于注释2中的d: 如果d['text']!='nan':#前提是在开头“import numpy.nan as nan” newrecord2.append(d) #打印新记录

@user1672063:以下是解决你问题的方法:

# let name your initial record "record"
# record = [{'yanchor': 'bottom', 'xanchor': 'auto', 'x': u'2018-Q3', 'y': 169.80000000000001, 'text': '169.8', 'showarrow': False},..]
#
# Let initialise a new record
newrecord = []
for d in record:
    if d['y'] is nan:   # provided that you "import numpy.nan as nan" at the beginning
       del d['y']
    newrecord.append(d)

#“newrecord”对应没有d[y]=nan的新记录

相关问题 更多 >