Skip to content

Commit

Permalink
Merge pull request #78 from martinRenou/nat_support_from_df
Browse files Browse the repository at this point in the history
Add NaT support in from_dataframe
  • Loading branch information
martinRenou committed Mar 13, 2019
2 parents 267ec40 + 1940d71 commit 9d4c663
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
4 changes: 3 additions & 1 deletion examples/pandas.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
" 'E': pd.Categorical([\"test\", \"train\", \"test\", \"train\"]),\n",
" 'F': 'foo'})\n",
"\n",
"df2.loc[[0, 2], ['B']] = np.nan\n",
"\n",
"sheet2 = from_dataframe(df2)\n",
"sheet2"
]
Expand Down Expand Up @@ -61,7 +63,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
"version": "3.6.7"
}
},
"nbformat": 4,
Expand Down
4 changes: 3 additions & 1 deletion ipysheet/pandas_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ def _format_date(date):


def _get_cell_value(arr):
import pandas as pd

if (arr.dtype.kind == 'M'):
return [_format_date(date) for date in arr]
return [_format_date(date) if not pd.isna(date) else None for date in arr]
else:
return arr.tolist()

Expand Down
23 changes: 22 additions & 1 deletion ipysheet/test_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,12 +436,14 @@ def test_from_dataframe():
'S': pd.Categorical(["test", "train", "test", "train"]),
'T': 'foo'})

df.loc[[0, 2], ['B']] = np.nan

sheet = ipysheet.from_dataframe(df)
assert len(sheet.cells) == 6
assert sheet.column_headers == ['A', 'B', 'C', 'D', 'S', 'T']
assert sheet.cells[0].value == [1., 1., 1., 1.]
assert sheet.cells[0].type == 'numeric'
assert sheet.cells[1].value == ['2013/01/02', '2013/01/02', '2013/01/02', '2013/01/02']
assert sheet.cells[1].value == [None, '2013/01/02', None, '2013/01/02']
assert sheet.cells[1].type == 'date'
assert sheet.cells[2].value == [1., 1., 1., 1.]
assert sheet.cells[2].type == 'numeric'
Expand All @@ -453,6 +455,25 @@ def test_from_dataframe():
assert sheet.cells[5].type == 'text'


def test_from_to_dataframe():
df = pd.DataFrame({
'A': 1.,
'B': pd.Timestamp('20130102'),
'C': pd.Series(1, index=list(range(4)), dtype='float32'),
'D': np.array([False, True, False, False], dtype='bool'),
'S': pd.Categorical(["test", "train", "test", "train"]),
'T': 'foo'})

df.loc[[0, 2], ['B']] = np.nan

sheet = ipysheet.from_dataframe(df)
df2 = ipysheet.to_dataframe(sheet)

a = np.array(df.values)
b = np.array(df2.values)
assert ((a == b) | (pd.isna(a) & pd.isna(b))).all()


def test_to_array():
sheet = ipysheet.sheet(rows=5, columns=4)
ipysheet.cell(0, 0, value=True)
Expand Down

0 comments on commit 9d4c663

Please sign in to comment.