Skip to content

BUG: Dask dataframe cannot handle string index #3269

Closed

Description

@ArcticLampyrid

I write the following code,but it doesn't work.

import dask.bag as db
import dask.dataframe as dd
import dask.array as da
import pandas as pd
if __name__ == '__main__':
	#Just for test
	pWord = dd.from_pandas(pd.DataFrame({'word':["a","b","c","bc","abc"],'probability':[0.1,0.2,0.3,0.4,0.5]}),npartitions=3)
	wordInfoTable = dd.from_pandas(pd.DataFrame({'word':["bc","abc"]}),npartitions=3)
	pWord = pWord.set_index(pWord.word)
	pIfRandom = pWord.loc[wordInfoTable.word.str.slice(stop=1)].probability.reset_index(drop=True) * pWord.loc[wordInfoTable.word.str.slice(start=1)].probability.reset_index(drop=True)
	wordInfoTable["adhesiveness"] = pWord.loc[wordInfoTable.word].probability.reset_index(drop=True) / pIfRandom
	print(wordInfoTable.compute())

The following code works well, but very slow

import dask.bag as db
import dask.dataframe as dd
import dask.array as da
import pandas as pd
if __name__ == '__main__':
	#Just for test
	pWord = dd.from_pandas(pd.DataFrame({'word':["a","b","c","bc","abc"],'probability':[0.1,0.2,0.3,0.4,0.5]}),npartitions=3)
	wordInfoTable = dd.from_pandas(pd.DataFrame({'word':["bc","abc"]}),npartitions=3)
	pWord = pWord.set_index(pWord.word)
	def getP(t):
		return next(pWord.loc[t].itertuples()).probability
	def applyAdhesiveness(row):
		word = row["word"]
		pIfRandom = getP(word[0]) * getP(word[1:])
		adhesiveness = getP(word) / pIfRandom
		row["adhesiveness"] = adhesiveness
		return row
	wordInfoTable["adhesiveness"] = None
	wordInfoTable = wordInfoTable.apply(applyAdhesiveness,axis=1,meta=wordInfoTable._meta)
	print(wordInfoTable.compute())

I know it may be not a suitable place to ask for help here, but I think it's the only place which I can get the answer.

Activity

  1. ArcticLampyrid commented on Mar 11, 2018

    @ArcticLampyrid
    Author

    When I try to use pWord.loc[wordInfoTable.word.str.slice(stop=1)]
    The code doesn't work.

  2. gabrielelanaro commented on Mar 11, 2018

    @gabrielelanaro
    Contributor

    pWord is indexed over word column. While wordInfoTable is indexed over some random integer index

  3. changed the title [-]How to call DataFrame.loc() with row labels in a delayed array?[/-] [+]How to call Series.isin() or DataFrame.loc() with multiple row labels in a delayed Series?[/+] on Mar 11, 2018
  4. gabrielelanaro commented on Mar 11, 2018

    @gabrielelanaro
    Contributor

    I think the problem is related to strings, I believe it's a bug in dask handling of string indices.

    import dask.dataframe as dd
    import pandas as pd
    
    a = dd.from_pandas(pd.DataFrame({'x':[0.1,0.2,0.3,0.4,0.5]}, index=["a","b","c","bc","abc"]), npartitions=3)
    b = dd.from_pandas(pd.DataFrame({'word':["bc","abc"]}), npartitions=3)
    a.loc[b.word]
    
    TypeError: '<' not supported between instances of 'int' and 'str'
    

    Another issue happens even with standard pd.Series

    import dask.dataframe as dd
    import pandas as pd
    
    a = dd.from_pandas(pd.DataFrame({'x':[0.1,0.2,0.3,0.4,0.5]}, index=["a","b","c","bc","abc"]), npartitions=3)
    b = pd.DataFrame({'word':["bc","abc"]})
    a.loc[b.word]
    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
    
    
  5. changed the title [-]How to call Series.isin() or DataFrame.loc() with multiple row labels in a delayed Series?[/-] [+]How to call Series.loc() or DataFrame.loc() with multiple row labels in a delayed Series?[/+] on Mar 11, 2018
  6. ArcticLampyrid commented on Mar 11, 2018

    @ArcticLampyrid
    Author

    @gabrielelanaro
    When both a and b are the type from pandas

    import pandas as pd
    
    a = pd.DataFrame({'x':[0.1,0.2,0.3,0.4,0.5]}, index=["a","b","c","bc","abc"])
    b = pd.DataFrame({'word':["bc","abc"]})
    print(a.loc[b.word])

    It can work well

  7. mrocklin commented on Mar 11, 2018

    @mrocklin
    Member

    Thanks for the minimal example in #3269 (comment) @gabrielelanaro !

    I agree that this looks like a bug in dask dataframe. When we call loc on a dask.dataframe.Series we are currently trying to align the two dataframe/series objects by divisions, which is where the exception is occurring. Instead we actually need to do a more complex operation where every partition of the indexer talks to every partition of the indexed.

    This should be fixed if anyone has interest.

    It's worth pointing out though that this will never be nearly as fast as in the Pandas case.

  8. gabrielelanaro commented on Mar 11, 2018

    @gabrielelanaro
    Contributor

    I've been experimenting with this issue on my local copy. I would say the main issue is that DataFrame.map_partitions does not actually just map a functions to all partitions in the dataframe, but it also performs some alignment under the hood. That's because it dispatches to core.map_partitions which perform alignment automatically (a more specific name would be map_aligned_partitions)

    I feel the best way to do this is to actually implement different versions of
    map_partitions:

    Something on these lines:

    1. "align" version, will take the _Frame arguments and align their index
    2. "forward" version, which will forward the arguments unchanged (warning: this could blow up)
    3. "broadcast" version, which will do the complex operation you were referring to. So the function will be applied to "paired partitions"l

    With regard to the present issue, if the Series is of type bool, you need to align partitions, otherwise, you need to broadcast and concat the results

  9. OliverHofkens commented on Jan 15, 2020

    @OliverHofkens

    Sorry for the necro, just wanted to put my 2 cents in.
    I ran into this problem when I wanted to select the groupwise minima over a certain column like this:

    indexes = df.groupby("grp")["val"].idxmin()
    df.loc[indexes]
    

    I implemented the suggested fix of having a broadcast_map_partitions() function which maps the given function over all combinations of partitions. I implemented this naively by copying map_partitions, removing the alignment that happens, and changing partitionwise_graph to create a partition-to-partition graph. This worked great, but memory usage was insane. My adaptive cluster peaked at 11 terabyte of memory usage on a calculation that previously spiked at ~100 gigs. I guess each partition is copied to the worker where each other partition lives? Might be an oversight in my implementation too, but at least it worked.

    Anyway, I found that just relying on Dask's divisions and alignment works way better.

    def _loc(_part, _selector_part):
        try:
            return _part.loc[_part.index.intersection(_selector_part)]
        except KeyError:
             return []
    
    indexes = df.groupby("grp")["val"].idxmin()
    indexes_partitioned = indexes.to_frame().set_index("val", drop=False)["val"]
    df.map_partitions(_loc, indexes_partitioned)
    

    On my big dataset, this takes the same time but uses ~100x less memory. And in my specific case, I could even cut out the extra steps by combining idxmin and loc in a single pass using groupby()._aca_agg() directly.

  10. GenevieveBuckley commented on Oct 12, 2021

    @GenevieveBuckley
    Contributor

    @dask/maintenance can someone edit the title of this issue to better reflect the contents? I'd suggest something like "BUG: Dask dataframe cannot handle string index"

    A minimal, reproducible example for this issue is given here: #3269 (comment)

  11. changed the title [-]How to call Series.loc() or DataFrame.loc() with multiple row labels in a delayed Series?[/-] [+]BUG: Dask dataframe cannot handle string index[/+] on Oct 12, 2021
  12. martindurant commented on Oct 12, 2021

    @martindurant
    Member

    (title updated)

  13. jsignell commented on Oct 13, 2021

    @jsignell
    Member

    This is an issue that I think could be pretty decently handled with a good explanation in an error message. I am opening a PR with one option.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions