Repository navigation
Description
What happened:
When concatenating row-wise dataframes ([ddf1, ddf2, ..., ddfN]) that do not have any overlap, but that naturally follow each other (so ddf1.divisions[-1] == ddf2.divisions[0], and ddf2.divisions[-1] == ddf3.divisions[0], and so on), dd.multi.concat clears divisions when it shouldn't.
What you expected to happen:
The concatenated result should have divisions ([ddf1.divisions[0], ..., ddf1.divisions[-2], ddf2.divisions[0], ..., ddf2.divisions[-2], ddf3.divisions[0], ..., ddfN.divisions[-2], ddfN.divisions[-1]]).
Minimal Complete Verifiable Example:
import dask.dataframe as dd
import pandas as pd
# Initial data
df = pd.DataFrame({
"date": pd.date_range("2019-01-01", "2019-01-10"),
"col1": range(0, 10),
"col2": range(9, -1, -1)
})
# To Dask, but it's not partitioned properly...
ddf = dd.from_pandas(df, npartitions=10) # this causes 9 partitions instead of 10!
if ddf.npartitions != 10:
print(f"ddf has {ddf.npartitions} partitions instead of 10!") # print instead of raising error, but why does this happen?
print(ddf.divisions) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), but a 10 should have been added as divisions[-1]!
# Index by date forcing 10 partitions
ddf = ddf.set_index("date", divisions=tuple(pd.date_range("2019-01-01", "2019-01-11"))) # note the 11th here!
assert ddf.npartitions == 10, "After repartitioning doesn't have 10 partitions!"
assert ddf.known_divisions, "Divisions should be known!"
assert list(ddf.divisions[:-1]) == df["date"].to_list(), "There should be one division per day!" # note last one omitted!
# Concatenate its partitions (Dask dataframes themselves) row-wise
dfs = [p for p in ddf.partitions]
res = dd.concat(dfs, axis=0)
if ddf.npartitions != 10:
print(f"concatenated has {res.npartitions} partitions instead of 10!")
assert res.known_divisions, "Should have kept divisions!" # this raises AssertionErrorAnything else we need to know?:
Looking into concat code, I think the solution is really simple. Here is the conflictive part:
if all(df.known_divisions for df in dasks):
# each DataFrame's division must be greater than previous one
if all(
dfs[i].divisions[-1] < dfs[i + 1].divisions[0]
for i in range(len(dfs) - 1)
):
divisions = []
for df in dfs[:-1]:
# remove last to concatenate with next
divisions += df.divisions[:-1]
divisions += dfs[-1].divisions
return stack_partitions(dfs, divisions, join=join, ignore_order=ignore_order, **kwargs)
elif interleave_partitions:
return concat_indexed_dataframes(dfs, join=join, ignore_order=ignore_order, **kwargs)
else:
divisions = [None] * (sum(df.npartitions for df in dfs) + 1)
return stack_partitions(dfs, divisions, join=join, ignore_order=ignore_order, **kwargs)The thing is that the check in all uses a strict <, but if would suffice with <=, because it's fine that the beginning of the next frame equals the last division of the previous frame, since that last division is NOT included in the previous frame.
To prove this, if I call stack_partitions properly in the example above, things work:
from dask.dataframe.multi import stack_partitions
res = stack_partitions(dfs, divisions=tuple(pd.date_range("2019-01-01", "2019-01-11")), join="inner", ignore_order=False)
assert res.known_divisions, "Should have kept divisions!" # this is fine
assert list(res.divisions[:-1]) == df["date"].to_list(), "There should be one division per day!" # this is fine tooI don't know if this has been addressed in #8517 (@jsignell @gjoseph92), but in my opinion the example above proves that there's space for improvement:
- The delicate point is that
divisions[-1]by definition is a value that is NOT present in data (it should be the first value NOT to include), so it cannot be properly inferred unless it's a very easy case (e.g. a range). - Because of this,
from_pandasin the above example yields 9 partitions instead of 10 (with the last partition having 2 rows), even if the most natural way to partition that is 1 row per partition. This is a consequence of the fact thatdivisions[-1]cannot be inferred, plus the fact thatfrom_pandasdoesn't accept adivisionsargument! - Because of this, if I do afterwards
set_indexwithout specifying proper divisions, it keeps on having 9 partitions, andpartition_quantilesyields a strange result:
ddf.divisions
(Timestamp('2019-01-01 00:00:00'), Timestamp('2019-01-01 21:36:00'), Timestamp('2019-01-02 19:12:00'), Timestamp('2019-01-03 16:48:00'), Timestamp('2019-01-04 14:24:00'), Timestamp('2019-01-05 12:00:00'), Timestamp('2019-01-06 09:36:00'), Timestamp('2019-01-07 07:12:00'), Timestamp('2019-01-08 04:48:00'), Timestamp('2019-01-09 02:24:00'), Timestamp('2019-01-10 00:00:00'))So I suggest this course of action:
- Change the code of
concatwith<=. - See if there are other parts of code where this same error could be present.
- Think about whether
divisions[-1]is really necessary. Do we need to have it?- For searching, I think it should suffice to know that
partitions[i]has values in its index in the interval[divisions[i], divisions[i+1]), for all partitions except the last one. The last one we know it starts indivisions[-2], but it's open-ended. - However, this raises a symmetry question in the 1st partition. Perhaps there should be two
divisionsarrays:- Beginning of partitions: this would be the current
[divisions[0], ..., divisions[-2]], which is the same as[partitions[0].index[0], ..., partitions[-1].index[0]]. - End of partitions: this would be last values actually present in each partition's index:
[partitions[0].index[-1], ..., partitions[-1].index[-1]].
- Beginning of partitions: this would be the current
- So that we know that the
i-th partition has values in the closed (not semi-open) interval[beginning[i], end[i]]. - As a side effect, these 2 arrays have the same length than
partitions, instead of the current situation wherelen(divisions) == len(partitions) + 1.
- For searching, I think it should suffice to know that
- If we ignore the previous point and stick to one
divisionsarray whose size isnpartitions + 1, in my opinion:from_pandasshould accept adivisionsargument.- If it doesn't receive
divisionsand turns out that the resultingnpartitionsisn't the one requested by the user, at least raise a warning. In the example above, the user should know that instead of 10 partitions it decided to take 9!
Environment:
- Dask version: 2022.02.1
- Python version: 3.9.10
- Operating System: Ubuntu
- Install method (conda, pip, source): Pip
Activity
aomirolis commentedon Mar 26, 2022
Hi, I am new to this project but I would like to work on this issue.
jorloplaz commentedon Mar 28, 2022
Thank you @aomirolis . In this particular case if some core developer can confirm that the only place to change is where I suggest in
dd.concat(points 1 and 2) and that my understanding is correct, I don't mind doing it myself. It'd be just a single change, and perhaps some test checking that things work.Regarding the
divisionsdiscussion and passingdivisionstofrom_pandas(points 3 and 4), I'd also like to receive some feedback. Perhaps we could move those to specific feature demands.bryanwweber commentedon Mar 28, 2022
This implies to me that they do have overlap, since the last element of
ddf1is the same as the first element ofddf2. Can you clarify about that?jorloplaz commentedon Mar 28, 2022
They don't, because for the
i-th partition,divisions[i+1]is supposed to be the first element that is NOT included in the index of thei-th dataframe. See for example the documentation of set_index, when it says:However, in the specific doc about partitions, it claims:
Which I interpret as
divisions[-1]is actually a value included in the last partition. But this means an asymmetry:divisions[i](inclusive) anddivisions[i+1](exclusive).divisions[-2](inclusive) todivisions[-1](also inclusive).So in the example above, last partition would lie in
[50, 100]and not in[50, 100). This is why I suggest to unify things so that there's no ambiguity, either with:divisions[-1]is present in data or not. If it's a value that must be present in data, an error should be raised if settingdivisions[-1]to a value that isn't really there. And if it's a value that isn't there, one has the problem that it can't be automatically inferred from data...In any case, this doesn't affect the example I chose where
concatdoesn't work as expected, because the ambiguous behavior happens only for the last partition. All other partitions are clearly left-closed and right-open. You can play with data of your own to verify this is so.jsignell commentedon Mar 28, 2022
Thanks for writing this up and thinking about how this can be better @jorloplaz.
I tend to agree that keeping track of
minandmaxwould be more useful than keeping track of divisions. The more I have thought about divisions the more I am convinced that it is not reasonable to enforce that all partitions except the last one are unique. For instance it makes it impossible to split a partition where all the index values are the same into two partitions.In terms of your original suggestions:
How we calculate divisions internally is we calculate the min and max of every partition and then we take all the mins and the last max. So it seems a little risky to drop the
=.I'm sure there are.
This is a very interesting idea. But I don't really get how it would help in this case since if we only know the lower bound then there is no way to keep the divisions since we can't say anything about the overlap.
This seems totally reasonable.
This also seems reasonable.
@aomirolis - this issue is pretty involved and it's going to take a while to arrive at a solution 😄 . I recommend looking for a "good first issue" tag if you are interested in contributing sometime in the near future.
jorloplaz commentedon Mar 29, 2022
Thanks for revising @jsignell . I think the problem here is that we're mixing several concepts into one issue. Let me try to decompose them, basing on your comments:
Well, my understanding is that we ensure uniqueness in order to accelerate searches, e.g., when indexing with
loc. In my mind this is doing a kind ofbisect_leftof the value we're searching in thedivisionslist, then we know in which partition to look for that particular value, and then it's just callinglocon the particular dataframe that lies inside that partition. Is this so?True, but I think this is reasonable, because of the above. If several partitions could hold the same index value, then you wouldn't know easily in which ones to look for it, or you should look in all of them in a parallel way... Not sure if that's really convenient.
Anyway, if it turns out that all the index values are the same, that column doesn't really make sense as an index, does it? At least in SQL terms of what an index should be.
What can indeed happen is that as a result of this uniqueness, partition sizes are quite imbalanced in the dask dataframe, in the sense that there are partitions with many more rows than others. This is why in my company we coded a custom solution to try to rebalance this, by looking at
index.value_counts()and making partitions as equally row-sized as possible, while also maintaining uniqueness (remember my comment here).In short, I think that uniqueness is a good idea, but it has to be complemented with some smart rebalancing so that partition
lens are reasonably similar.Turning back to the
concatproblem:In this case I'm trying to concatenate several dataframes, each of which has data for a different day. And those are consecutive days, so clearly the resulting divisions should be the concatenation of the divisions of each dataframe.
In other words, for my example it'd be absolutely correct that the execution flow entered the
if all(...)and then calledstack_partitions. But it doesn't because there's a<in the condition and not a<=!The thing is that there's an inconsistency in
divisionsthat is causing these troubles:mins and the lastmax. Note that in this casedivisions[-1]is included in the last partition.divisionspassed on toset_index), it isn't checked thatdivisions[-1]is really themaxof the last partition. Actually, the doc encourages that it's a value that isn't there!I reproduce my example here. Notice how I passed
'2019-01-11'to bedivisions[-1], and it's set directly in the dataframe. But themaxis'2019-01-10'!So, the decomposition of this issue I think is:
divisions[-1]should be themaxof the last partition or not:concatcode with<is correct. If there's no overlap, it should hold thatdfs[i].divisions[-1] < dfs[i+1].divisions[0]and we can close this issue when we've covered points 2 and 3 below.<=.divisionsas inset_index, an error should be raised if what is passed doesn't comply with this logic of "the min of each partition and the last max". In particular, the last division passed should be a value that is present in the data!from_pandassupport adivisionsargument.divisionsshould be a single or a double array, and whether partitions should be unique or not.Do you agree?