【问题标题】:Pandas .sort_values() function returning data frame with scattered valuesPandas .sort_values() 函数返回具有分散值的数据框
【发布时间】:2022-11-29 15:18:05
【问题描述】:

我正在使用熊猫加载包含以下列的 short_desc.csv:["report_id", "when","what"]

#read csv
shortDesc = pd.read_csv('short_desc.csv') 

#get all numerical and nonnull values
shortDesc = shortDesc[shortDesc['report_id'].str.isdigit().notnull()]

#convert 'when' from UNIX timestamp to datetime
shortDesc['when'] = pd.to_datetime(shortDesc['when'],unit='s') 

结果如下:

我试图通过排序删除具有重复“report_id”的行 日期并获取包含“report_id”的最新日期:

shortDesc = shortDesc.sort_values(by='when').drop_duplicates(['report_id'], keep='last') 

问题是,当我在这个特定的数据框中使用 .sort_values() 时,“what”的值分散在所有列中,而“report_id”值消失了:

shortDesc = shortDesc.sort_values(by=['when'], inplace=False)

我不确定为什么会在这个特定实例中发生这种情况,因为我能够通过具有相同形状并使用相同代码的另一个数据框获得正确的结果(PS 这不是错误,我删除了“什么”列在第二张图):

相似形状数据框

具有相似形状 DF 的期望结果示例

【问题讨论】:

  • 它不是真的“分散在所有列中”,是吗?只是whatreport_id交换了位置。这真的是所有代码吗?
  • @TimRoberts 影响从“short_desc.csv”加载内容的代码,是的。此外,日期正在更改,在某些行中,“reported_id”列中的值和其他行中的“what”列中的值。我对发生的事情感到困惑。
  • 你能提供重现这个问题的数据吗?
  • @Frodnar & @Time Roberts,我弄清楚是什么导致 .sort_values() 函数关闭。 report_id 中有一个字符串值,在 shortDesc[shortDesc['report_id'].str.isdigit().notnull()] 中没有被检查,我假设因为它可能首先检查它是否是一个数字,然后如果它是一个数字则被更改,我将两个检查移动到两行,然后修复了它。我仍然对为什么 'report_id' 中的字符串值影响 .sort_values(by="when") 而 report_id 不应该与排序有任何关系感到困惑。

标签: python pandas dataframe


【解决方案1】:

我发现:

#get all numerical and nonnull values
shortDesc = shortDesc[shortDesc['report_id'].str.isdigit().notnull()]

只是检查一个值是否不为空并且可能覆盖 str.isdigit() 检查,这导致字段“report_id”不删除非数字值。我将其更改为两条单独的线

shortDesc = shortDesc[shortDesc['report_id'].notnull()]
shortDesc = shortDesc[shortDesc['report_id'].str.isnumeric()]

这允许

shortDesc.sort_values(by='when', inplace=True)

为了按预期工作,我仍然不明白为什么 .sort_values(by="when") 会受到列“report_id”的影响。所以有知道的请赐教。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2022-01-16
    • 2017-09-07
    相关资源
    最近更新 更多