Repository: pandas-dev/pandas

Issue:
Dropped categories when constructing Series or DF with categorical dtype, scalar data, and list index
#### Code Sample, a copy-pastable example if possible

```python

import pandas as pd

# You need >= pandas 0.21 for this to work.
from pandas.api.types import CategoricalDtype

# Create categorical type with three unordered categories for future use
cats = ['a', 'b', 'c']
catType = CategoricalDtype(categories=cats, ordered=False)

# Use categorical type to create series from list
s1 = pd.Series(['a', 'a'], dtype=catType)

# Use categorical type to create series from scalar with two element
# index (constructor does broadcasting)
s2 = pd.Series('a', index=s1.index, dtype=catType)

# I expect s1 and s2 to be identical. They are not.
print(s1)
print(s2) #notice only one category is shown for the dtype

# I can assign any member of the original categories to s1.
s1.loc[0] = 'c'

# However, this call will fail
try:
    s2.loc[0] = 'c'
except:
    print(" ")
    print("Code in try block fails because of dropped category members")
    print(" ")
    
# Work around: explicitly call add_categories to replace info lost by the constructor
s2.cat.add_categories(cats[1:], inplace=True)
s2.loc[0] = 'c'

```
#### Problem description

The constructors of both Series and DataFrame accept the combination of a scalar value and a n-element index. With given this calling syntax, they mimic numpy broadcasting/scalar expansion and repeat the scalar value n times to produce the object.

This behavior is broken by specifying a pre-defined categorical dtype. The dtype of the resulting pandas object will only have one category corresponding to the original scalar. All other categories associated with the dtype are lost.

If, rather, the constructor is called with n-element data and n-element index, all categories are retained in the dtype, even of they were not all included in the n-element data.

#### Expected Output

In the above code, I expect s1 and s2 to be identical. Further, I expect to be able to assign other category members to s2.

For s1 I get this expected output:
```
0    a
1    a
dtype: category
Categories (3, object): [a, b, c]
```
but for for s2 I get this output showing only 1 category member:
```
0    a
1    a
dtype: category
Categories (1, object): [a]
 ```

#### Output of ``pd.show_versions()``

<details>

[paste the output of ``pd.show_versions()`` here below this line]

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.3.final.0
python-bits: 64
OS: Windows
OS-release: 10
machine: AMD64
processor: Intel64 Family 6 Model 158 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: en_US.UTF-8
LOCALE: None.None

pandas: 0.22.0
pytest: 3.2.1
pip: 9.0.1
setuptools: 38.4.0
Cython: 0.26.1
numpy: 1.14.0
scipy: 0.19.1
pyarrow: None
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.2
feather: None
matplotlib: 2.1.2
openpyxl: 2.4.8
xlrd: 1.1.0
xlwt: 1.3.0
xlsxwriter: 1.0.2
lxml: 4.1.0
bs4: 4.6.0
html5lib: 0.999999999
sqlalchemy: 1.1.13
pymysql: None
psycopg2: None
jinja2: 2.9.6
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

</details>



Discussion:
Thanks, seems closely related (but distinct from) https://github.com/pandas-dev/pandas/issues/19342.

Let me know if you're interested in taking a look! We can point you in the right direction.

Resolving patch:
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1178,7 +1178,7 @@ def construct_1d_arraylike_from_scalar(value, length, dtype):
         subarr = DatetimeIndex([value] * length, dtype=dtype)
     elif is_categorical_dtype(dtype):
         from pandas import Categorical
-        subarr = Categorical([value] * length)
+        subarr = Categorical([value] * length, dtype=dtype)
     else:
         if not isinstance(dtype, (np.dtype, type(np.dtype))):
             dtype = dtype.dtype


Test patch:
diff --git a/pandas/tests/dtypes/test_cast.py b/pandas/tests/dtypes/test_cast.py
--- a/pandas/tests/dtypes/test_cast.py
+++ b/pandas/tests/dtypes/test_cast.py
@@ -22,7 +22,8 @@
     maybe_convert_string_to_object,
     maybe_convert_scalar,
     find_common_type,
-    construct_1d_object_array_from_listlike)
+    construct_1d_object_array_from_listlike,
+    construct_1d_arraylike_from_scalar)
 from pandas.core.dtypes.dtypes import (
     CategoricalDtype,
     DatetimeTZDtype,
@@ -422,3 +423,15 @@ def test_cast_1d_array(self, datum1, datum2):
     @pytest.mark.parametrize('val', [1, 2., None])
     def test_cast_1d_array_invalid_scalar(self, val):
         pytest.raises(TypeError, construct_1d_object_array_from_listlike, val)
+
+    def test_cast_1d_arraylike_from_scalar_categorical(self):
+        # GH 19565 - Categorical result from scalar did not maintain categories
+        # and ordering of the passed dtype
+        cats = ['a', 'b', 'c']
+        cat_type = CategoricalDtype(categories=cats, ordered=False)
+        expected = pd.Categorical(['a', 'a'], categories=cats)
+        result = construct_1d_arraylike_from_scalar('a', len(expected),
+                                                    cat_type)
+        tm.assert_categorical_equal(result, expected,
+                                    check_category_order=True,
+                                    check_dtype=True)
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -270,6 +270,13 @@ def test_constructor_categorical_dtype(self):
         tm.assert_index_equal(result.cat.categories, pd.Index(['b', 'a']))
         assert result.cat.ordered is False
 
+        # GH 19565 - Check broadcasting of scalar with Categorical dtype
+        result = Series('a', index=[0, 1],
+                        dtype=CategoricalDtype(['a', 'b'], ordered=True))
+        expected = Series(['a', 'a'], index=[0, 1],
+                          dtype=CategoricalDtype(['a', 'b'], ordered=True))
+        tm.assert_series_equal(result, expected, check_categorical=True)
+
     def test_categorical_sideeffects_free(self):
         # Passing a categorical to a Series and then changing values in either
         # the series or the categorical should not change the values in the