Skip to content

Commit 3f56aa4

Browse files
authored
Merge pull request #675 from plotly/grid-accept-dataframe
Grid Accept Dataframe
2 parents ddcebd6 + 83942eb commit 3f56aa4

File tree

3 files changed

+49
-2
lines changed

3 files changed

+49
-2
lines changed

plotly/grid_objs/grid_objs.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99

1010
from requests.compat import json as _json
1111

12-
from plotly import exceptions, utils
12+
from plotly import exceptions, optional_imports, utils
13+
14+
pd = optional_imports.get_module('pandas')
1315

1416
__all__ = None
1517

@@ -148,7 +150,20 @@ def __init__(self, columns_or_json, fid=None):
148150
```
149151
"""
150152
# TODO: verify that columns are actually columns
151-
if isinstance(columns_or_json, dict):
153+
if pd and isinstance(columns_or_json, pd.DataFrame):
154+
duplicate_name = utils.get_first_duplicate(columns_or_json.columns)
155+
if duplicate_name:
156+
err = exceptions.NON_UNIQUE_COLUMN_MESSAGE.format(duplicate_name)
157+
raise exceptions.InputError(err)
158+
159+
# create columns from dataframe
160+
all_columns = []
161+
for name in columns_or_json.columns:
162+
all_columns.append(Column(columns_or_json[name].tolist(), name))
163+
self._columns = all_columns
164+
self.id = ''
165+
166+
elif isinstance(columns_or_json, dict):
152167
# check that fid is entered
153168
if fid is None:
154169
raise exceptions.PlotlyError(

plotly/tests/test_optional/test_grid/__init__.py

Whitespace-only changes.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
test_grid:
3+
==========
4+
5+
A module intended for use with Nose.
6+
7+
"""
8+
from __future__ import absolute_import
9+
10+
from unittest import TestCase
11+
12+
from plotly.exceptions import InputError
13+
from plotly.grid_objs import Grid
14+
15+
import pandas as pd
16+
17+
18+
class TestDataframeToGrid(TestCase):
19+
20+
# Test duplicate columns
21+
def test_duplicate_columns(self):
22+
df = pd.DataFrame([[1, 'a'], [2, 'b']],
23+
columns=['col_1', 'col_1'])
24+
25+
expected_message = (
26+
"Yikes, plotly grids currently "
27+
"can't have duplicate column names. Rename "
28+
"the column \"{}\" and try again.".format('col_1')
29+
)
30+
31+
with self.assertRaisesRegexp(InputError, expected_message):
32+
Grid(df)

0 commit comments

Comments
 (0)