Repository: pandas-dev/pandas

Issue:
SparseDataFrame with dense Series or unknown type
#### Code Sample, a copy-pastable example if possible

```python
import pandas

pandas.SparseDataFrame(pandas.Series())
```
#### Problem description

I've seen there are plans to SparseDataFrame. But reporting anyway.

The above code, creating a `SparseDataFrame` with a dense `Series` fails with a not very descriptive error:

```
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-6-b9708ff05a7c> in <module>()
      1 import pandas
      2 
----> 3 pandas.SparseDataFrame(pandas.Series())

~/anaconda3/lib/python3.6/site-packages/pandas/core/sparse/frame.py in __init__(self, data, index, columns, default_kind, default_fill_value, dtype, copy)
    120                 mgr = mgr.astype(dtype)
    121 
--> 122         generic.NDFrame.__init__(self, mgr)
    123 
    124     @property

UnboundLocalError: local variable 'mgr' referenced before assignment
```

Any other type provided to the constructor fails with the same error.

#### Expected Output

I'd expect an empty series (if the dense `Series` has a name, or columns is provided).

Or a useful error message, if the data type is not accepted.

#### Output of ``pd.show_versions()``

<details>

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.4.final.0
python-bits: 64
OS: Linux
OS-release: 4.14.13-300.fc27.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: en_GB.utf8
LOCALE: en_GB.UTF-8

pandas: 0.23.0.dev0+152.g2952fbd55.dirty
pytest: 3.3.0
pip: 9.0.1
setuptools: 36.5.0.post20170921
Cython: 0.27.3
numpy: 1.13.3
scipy: 1.0.0
pyarrow: 0.7.1
xarray: None
IPython: 6.2.1
sphinx: 1.6.3
patsy: 0.4.1
dateutil: 2.6.1
pytz: 2017.3
blosc: None
bottleneck: 1.2.1
tables: 3.4.2
numexpr: 2.6.4
feather: None
matplotlib: 2.1.1
openpyxl: 2.4.9
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 1.0.2
lxml: 4.1.1
bs4: 4.6.0
html5lib: 1.0.1
sqlalchemy: 1.1.13
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

</details>



Discussion:

Resolving patch:
diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py
--- a/pandas/core/sparse/frame.py
+++ b/pandas/core/sparse/frame.py
@@ -95,6 +95,9 @@ def __init__(self, data=None, index=None, columns=None, default_kind=None,
                                  dtype=dtype, copy=copy)
         elif isinstance(data, DataFrame):
             mgr = self._init_dict(data, data.index, data.columns, dtype=dtype)
+        elif isinstance(data, Series):
+            mgr = self._init_dict(data.to_frame(), data.index,
+                                  columns=None, dtype=dtype)
         elif isinstance(data, BlockManager):
             mgr = self._init_mgr(data, axes=dict(index=index, columns=columns),
                                  dtype=dtype, copy=copy)
@@ -116,6 +119,10 @@ def __init__(self, data=None, index=None, columns=None, default_kind=None,
             mgr = to_manager(data, columns, index)
             if dtype is not None:
                 mgr = mgr.astype(dtype)
+        else:
+            msg = ('SparseDataFrame called with unkown type "{data_type}" '
+                   'for data argument')
+            raise TypeError(msg.format(data_type=type(data).__name__))
 
         generic.NDFrame.__init__(self, mgr)
 


Test patch:
diff --git a/pandas/tests/sparse/frame/test_frame.py b/pandas/tests/sparse/frame/test_frame.py
--- a/pandas/tests/sparse/frame/test_frame.py
+++ b/pandas/tests/sparse/frame/test_frame.py
@@ -199,6 +199,29 @@ def test_constructor_from_series(self):
         # without sparse value raises error
         # df2 = SparseDataFrame([x2_sparse, y])
 
+    def test_constructor_from_dense_series(self):
+        # GH 19393
+        # series with name
+        x = Series(np.random.randn(10000), name='a')
+        result = SparseDataFrame(x)
+        expected = x.to_frame().to_sparse()
+        tm.assert_sp_frame_equal(result, expected)
+
+        # series with no name
+        x = Series(np.random.randn(10000))
+        result = SparseDataFrame(x)
+        expected = x.to_frame().to_sparse()
+        tm.assert_sp_frame_equal(result, expected)
+
+    def test_constructor_from_unknown_type(self):
+        # GH 19393
+        class Unknown:
+            pass
+        with pytest.raises(TypeError,
+                           message='SparseDataFrame called with unkown type '
+                                   '"Unknown" for data argument'):
+            SparseDataFrame(Unknown())
+
     def test_constructor_preserve_attr(self):
         # GH 13866
         arr = pd.SparseArray([1, 0, 3, 0], dtype=np.int64, fill_value=0)