【问题标题】:Replace NaNs with unique reference in Pandas data frame用 Pandas 数据框中的唯一引用替换 NaN
【发布时间】:2021-11-24 17:49:15
【问题描述】:

我有一个缺少唯一引用的数据框,我想在数据集中为这些生成唯一引用。我想我会为此使用索引/行值,因为它是一个增量数字,但我只需要任何改变的数字。

到目前为止,我已经设法创建了一个列来获取索引值(当然我可能不必这样做,但这是我最接近让它工作的):

# Create column with the index values so they can be used to create unique refs for missing planning references
ah_df['Index Values'] = ah_df.index.values

然后我尝试在尝试替换 NaN 时引用它,为我的每个新引用提供前缀“未知 Ref”:

# Creates unique references to replace the blanks
ah_df.loc[ah_df["Planning Reference"].isnull(),'Planning Reference'] = "Unknown Ref" + str(ah_df['Index Values'])

只要它给了我一些东西,这个“有效”,但索引位没有给我预期的增量数字。相反,我得到了这个:

“未知 Ref0 0\n1 1\n2 2.”

我做错了什么?

谢谢:)

【问题讨论】:

    标签: python pandas indexing


    【解决方案1】:

    要转换为字符串,请使用Series.astype:

    ah_df.loc[ah_df["Planning Reference"].isnull(),'Planning Reference'] = "Unknown Ref" + ah_df['Index Values'].astype(str)
    

    或者不需要新列,使用Index.astype:

    ah_df.loc[ah_df["Planning Reference"].isnull(),'Planning Reference'] = "Unknown Ref" + ah_df.index.astype(str)
    

    如果需要0 的计数器,仅适用于NaNs:

    m = ah_df["Planning Reference"].isnull()
    ah_df.loc[m,'Planning Reference'] = [f"Unknown Ref{i}" for i in range(m.sum)]
    

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 2018-11-08
      • 2017-12-03
      • 2016-10-16
      • 2022-10-05
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      相关资源
      最近更新 更多