【发布时间】: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 这不是错误,我删除了“什么”列在第二张图):
【问题讨论】:
-
它不是真的“分散在所有列中”,是吗?只是
what和report_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 不应该与排序有任何关系感到困惑。