嗨,看起来大家都很困惑,所以我取消了尝试,只留下了问题中非常相关的部分:
创建数据帧的代码:
Sample = [{'account': 'Jones LLC', 'Jan': 150, 'Feb': 200, 'Mar': [.332, .326, .329]},
{'account': 'Alpha Co', 'Jan': 200, 'Feb': 210, 'Mar': [[.234, .246], None]},
{'account': 'Blue Inc', 'Jan': 50, 'Feb': 90, 'Mar': [[.23], [.745, .398, .923], None] }]
df = pd.DataFrame(Sample)
可视化数据帧:
df:
account Jan Feb Mar
Jones LLC | 150 | 200 | [.332, .326, .329]
Alpha Co | 200 | 210 | [[.234, .246], None]
Blue Inc | 50 | 90 | [[.23], [.745, .398, .923], None]
我需要一个可以应用于df的函数来从df['mar']中删除“none”值,目的是返回:
df:
account Jan Feb Mar
Jones LLC | 150 | 200 | [.332, .326, .329]
Alpha Co | 200 | 210 | [.234, .246]
Blue Inc | 50 | 90 | [.23], [.745, .398, .923]
最佳答案
您可以嵌套列表理解:df['Mar'] = [[x for x in inner_list if x is not None] for inner_list in df['Mar']]
您还可以使用filter
筛选出None
值df['Mar'] = [list(filter(lambda x: x is None, inner_list)) for inner_list in df['Mar']]