【问题标题】:Replace empty dictionaries and lists from within pandas dataframe with Null用 Null 替换 pandas 数据框中的空字典和列表
【发布时间】:2020-05-20 13:38:03
【问题描述】:

我有一个数据框,其中包含列中的列表和字典。我将如何编写一个可以应用于需要将空字典和列表替换为 Null 的列的函数?

def transform_empty_cells(column):
    df.loc[(df.column == [] or {}),'column'] = 'Null'

尝试制作一个简洁的函数,而不必为每一列编写一行代码。

将函数映射到我需要应用它的列会很好。有什么想法吗?

【问题讨论】:

    标签: python pandas list dictionary null


    【解决方案1】:

    让我们尝试使用bool,因为空的dictlist 将被转换为False

    df.loc[~df.column.astype(bool),'column']='null'
    

    更多栏目

    df=pd.DataFrame({'Data':[[],[1]],'dct':[{},{1:2}]})
    s=df.where(df.astype(bool))
    s
    Out[24]: 
      Data     dct
    0  NaN     NaN
    1  [1]  {1: 2}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-22
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2022-01-24
      • 1970-01-01
      • 2021-11-14
      相关资源
      最近更新 更多