Skip to content

Commit 1320156

Browse files
committed
ENH: Enable DataFrame to accept scalar constructor values like Series #1856
1 parent 2b36acd commit 1320156

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

pandas/core/frame.py

+19-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from pandas.core.indexing import _NDFrameIndexer, _maybe_droplevels
3232
from pandas.core.internals import (BlockManager, make_block, form_blocks,
3333
IntBlock)
34-
from pandas.core.series import Series, _radd_compat
34+
from pandas.core.series import Series, _radd_compat, _dtype_from_scalar
3535
from pandas.compat.scipy import scoreatpercentile as _quantile
3636
from pandas.util import py3compat
3737
from pandas.util.terminal import get_terminal_size
@@ -417,7 +417,24 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
417417
mgr = self._init_ndarray(data, index, columns, dtype=dtype,
418418
copy=copy)
419419
else:
420-
raise PandasError('DataFrame constructor not properly called!')
420+
try:
421+
arr = np.array(data, dtype=dtype, copy=copy)
422+
except (ValueError, TypeError):
423+
raise PandasError('DataFrame constructor called with '
424+
'incompatible data and dtype')
425+
426+
if arr.ndim == 0 and index is not None and columns is not None:
427+
if isinstance(data, basestring) and dtype is None:
428+
dtype = np.object_
429+
if dtype is None:
430+
data, dtype = _dtype_from_scalar(data)
431+
432+
values = np.empty((len(index), len(columns)), dtype=dtype)
433+
values.fill(data)
434+
mgr = self._init_ndarray(values, index, columns, dtype=dtype,
435+
copy=False)
436+
else:
437+
raise PandasError('DataFrame constructor not properly called!')
421438

422439
NDFrame.__init__(self, mgr)
423440

pandas/tests/test_frame.py

+16
Original file line numberDiff line numberDiff line change
@@ -2383,6 +2383,22 @@ def test_constructor_column_duplicates(self):
23832383
[('a',[8]),('a',[5]), ('b', [6])],
23842384
columns=['b', 'a','a'])
23852385

2386+
def test_constructor_single_value(self):
2387+
df = DataFrame(0., index=[1,2,3], columns=['a','b','c'])
2388+
assert_frame_equal(df, DataFrame(np.zeros(df.shape), df.index,
2389+
df.columns))
2390+
2391+
df = DataFrame('a', index=[1,2], columns=['a', 'c'])
2392+
assert_frame_equal(df, DataFrame(np.array([['a', 'a'],
2393+
['a', 'a']],
2394+
dtype=object),
2395+
index=[1,2],
2396+
columns=['a', 'c']))
2397+
2398+
self.assertRaises(com.PandasError, DataFrame, 'a', [1,2])
2399+
self.assertRaises(com.PandasError, DataFrame, 'a', columns=['a' ,'c'])
2400+
self.assertRaises(com.PandasError, DataFrame, 'a', [1,2], ['a', 'c'], float)
2401+
23862402
def test_new_empty_index(self):
23872403
df1 = DataFrame(randn(0, 3))
23882404
df2 = DataFrame(randn(0, 3))

0 commit comments

Comments
 (0)