Skip to content

Pandas DF column names can be complex objects in Python #274

Closed
@DavisVaughan

Description

@DavisVaughan

Oddly, column names in a pandas DF (and lower level, in a dict()), can be complex objects, not just strings. This causes some issue with object conversion, but I think there is a solution with x$columns$format().

library(reticulate)

pd <- import("pandas", convert = FALSE)

d <- dict("col1" = list(1,2))

# Strange key where the key is actually a tuple
odd_key <- tuple("col1", "col2")
d[odd_key] = list(4,5)

d
#> {('col1', 'col2'): [4.0, 5.0], 'col1': [1.0, 2.0]}

# Strange df where the column name is actually a tuple
x = pd$DataFrame(data=d)

x
#>    col1  (col1, col2)
#> 0   1.0           4.0
#> 1   2.0           5.0

class(x$columns$values[[1]])
#> [1] "python.builtin.tuple"  "python.builtin.object"

py_to_r(x)
#> Error in py_call_impl(callable, dots$args, dots$keywords): KeyError: "['col2'] not in index"
#> 
#> Detailed traceback: 
#>   File "/Users/davisvaughan/.virtualenvs/r-reticulate/lib/python2.7/site-packages/pandas/core/frame.py", line 1991, in __getitem__
#>     return self._getitem_array(key)
#>   File "/Users/davisvaughan/.virtualenvs/r-reticulate/lib/python2.7/site-packages/pandas/core/frame.py", line 2035, in _getitem_array
#>     indexer = self.ix._convert_to_indexer(key, axis=1)
#>   File "/Users/davisvaughan/.virtualenvs/r-reticulate/lib/python2.7/site-packages/pandas/core/indexing.py", line 1214, in _convert_to_indexer
#>     raise KeyError('%s not in index' % objarr[mask])

# # debug with...
#debugonce(reticulate:::py_to_r.pandas.core.frame.DataFrame)
#py_to_r(x)

# Potential solution?
x$columns$format()
#> [u'col1', u'(col1, col2)']

Created on 2018-05-21 by the reprex package (v0.2.0).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions