为什么这两组运算之间没有顺序不变性?

2024-09-30 01:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个CSV文件/dataframe,其中第一列包含日期。 我想在这里做一些转换到datetime,一些过滤,排序和重新索引

我的经验是,如果我改变操作集的顺序,我会得到不同的结果(第一个配置的结果比另一个更大)。可能第一个是“好”的

谁能告诉我,哪些子操作导致了结果之间的差异

哪一个是“坏”的,哪一个是“好”的解决方案

在用户可以按任意顺序调用这两个方法并仍然得到良好结果的情况下,是否可能实现安全的顺序独立性(是否可以通过实现可互换的操作集来获得好的结果?)

jdf1 = x.copy(deep=True)
jdf2 = x.copy(deep=True)
interval = [DATE_START, DATE_END]
dateColName = "Date"

配置1:

# Operation set 1: dropping duplicates, sorting and reindexing the table
jdf1.drop_duplicates(subset=dateColName, inplace=True)
jdf1.sort_values(dateColName, inplace=True)
jdf1.reset_index(drop=True, inplace=True)

# Operatrion set 2: converting column type and filtering the rows in case of CSV's contents are covering a wider interval
jdf1[dateColName] = pd.to_datetime(jdf1[jdf1.columns[0]], format="%Y-%m-%d")
maskL = jdf1[dateColName] < interval[0]
maskR = jdf1[dateColName] > interval[1]
mask = maskL | maskR
jdf1.drop(jdf1[mask].index, inplace=True)

配置2:

# Operatrion set 2: converting column type and filtering the rows in case of CSV's contents are covering a wider interval
jdf2[dateColName] = pd.to_datetime(jdf2[jdf2.columns[0]], format="%Y-%m-%d")
maskL = jdf2[dateColName] < interval[0]
maskR = jdf2[dateColName] > interval[1]
mask = maskL | maskR
jdf2.drop(jdf2[mask].index, inplace=True)

# Operation set 1: dropping duplicates, sorting and reindexing the table
jdf2.drop_duplicates(subset=dateColName, inplace=True)
jdf2.sort_values(dateColName, inplace=True)
jdf2.reset_index(drop=True, inplace=True)

结果:

val1 = set(jdf1["Date"].values)
val2 = set(jdf2["Date"].values)

# bigger:
val1 - val2

# empty:
val2 - val1

谢谢你的帮助


Tags: andthetrueindexdropduplicatesvaluesinterval
1条回答
网友
1楼 · 发布于 2024-09-30 01:24:02

乍一看是一样的,但不是

因为有两种不同的过滤方式可以相互影响:

drop_duplicates() -> remove M rows, together ALL rows - M
boolean indexing with mask -> remove N rows, together ALL - M - N

你知道吗

boolean indexing with mask -> remove K rows, together ALL rows - K
drop_duplicates() -> remove L rows, together ALL - K - L
K != M
L != N

如果交换这个操作,结果应该是不同的,因为两者都会删除行。调用它们的顺序很重要,因为有些行只删除drop\u重复项,有些行只删除布尔索引

在我看来这两种方法都是对的,这要看需要什么

相关问题 更多 >

    热门问题