【问题标题】:Pandas create multiple columns if not exist in different datasets (the datasets are values of a dictionary)如果不同数据集中不存在,熊猫会创建多个列(数据集是字典的值)
【发布时间】:2020-11-17 19:34:38
【问题描述】:

我有以下问题; 我有一个字典,每个值都包含一个数据集(附图片)as you will see 57796 and 34733 are the keys and the values are the datasets

所以每个数据集都有不同的列,但共享其中大部分 7 columns needed_cols = ["osmid", "geometry", "highway", "element_type", "oneway", "surface", "maxspeed"]

因此,我想做的是遍历每个数据集并为每个数据集保留这 7 列(仅这 7 列),并为没有 1、2、3 或没有这些列的数据集创建它们.

我认为递归 fn 是一个不错的选择,所以我创建了以下一个,它可以工作,但仅适用于第一个值,它不适用于其余的值。

def setCols(dic, arr):
for k in dic.keys():
    for col in arr:
        if col not in list(dic[k].columns):
            dic[k][col] = "null"
            return setCols(dic, arr)
        else:
            dic[k] = dic[k][arr]
            return dic

“dic”整个词典,“arr”“needed_cols” 据我了解,此递归 fn 应检查“needed_cols”的每个值是否在每个数据集中,如果不是,则使用“null”值创建它并再次启动 fn,直到数据集具有所有“neede_cols”,或者,在另一个站点上,如果数据集已经包含所有“needed_cols”,则返回字典,每个数据集只有“needed_cols”

提前致谢

【问题讨论】:

    标签: python-3.x pandas dataframe dictionary recursion


    【解决方案1】:

    我发现了错误..这是一个识别问题,实际上 while 更有意义:

    def setCols(dic, arr):
        for k in dic.keys():
            for col in arr:
                while col not in list(dic[k].columns):
                    print("column doesn't exist")
                    dic[k][col] = "null"
                    print("column created")
            
            dic[k] = dic[k][arr]
            print("it is ok")
            
        return dic
    

    【讨论】:

      猜你喜欢
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2018-02-26
      相关资源
      最近更新 更多