Skip to content

Commit 3027871

Browse files
Chang Shewesm
authored andcommitted
ENH: retain Series names when constructing DataFrame from list of Series #1494
1 parent e209185 commit 3027871

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

pandas/core/frame.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,9 @@ def __init__(self, data=None, index=None, columns=None, dtype=None,
389389
copy=copy)
390390
elif isinstance(data, list):
391391
if len(data) > 0:
392+
if index is None and isinstance(data[0], Series):
393+
index = _get_names_from_index(data)
394+
392395
if isinstance(data[0], (list, tuple, dict, Series)):
393396
conv_data, columns = _to_sdict(data, columns)
394397
if isinstance(conv_data, dict):
@@ -4758,6 +4761,22 @@ def _convert_object_array(content, columns, coerce_float=False):
47584761
for c, vals in zip(columns, content))
47594762
return sdict, columns
47604763

4764+
def _get_names_from_index(data):
4765+
index = range(len(data))
4766+
has_some_name = any([s.name is not None for s in data])
4767+
if not has_some_name:
4768+
return index
4769+
4770+
count = 0
4771+
for i, s in enumerate(data):
4772+
n = s.name
4773+
if n is not None:
4774+
index[i] = n
4775+
else:
4776+
index[i] = 'Unnamed %d' % count
4777+
count += 1
4778+
4779+
return index
47614780

47624781
def _homogenize(data, index, columns, dtype=None):
47634782
from pandas.core.series import _sanitize_array

pandas/tests/test_frame.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1871,6 +1871,28 @@ def test_constructor_list_of_dicts(self):
18711871
assert_frame_equal(result, expected)
18721872

18731873
def test_constructor_list_of_series(self):
1874+
data = [{'a': 1.5, 'b': 3.0, 'c':4.0},
1875+
{'a': 1.5, 'b': 3.0, 'c':6.0}]
1876+
sdict = dict(zip(['x', 'y'], data))
1877+
idx = Index(['a', 'b', 'c'])
1878+
1879+
# all named
1880+
data2 = [Series([1.5, 3, 4], idx, dtype='O', name='x'),
1881+
Series([1.5, 3, 6], idx, name='y')]
1882+
result = DataFrame(data2)
1883+
expected = DataFrame.from_dict(sdict, orient='index')
1884+
assert_frame_equal(result, expected)
1885+
1886+
# some unnamed
1887+
data2 = [Series([1.5, 3, 4], idx, dtype='O', name='x'),
1888+
Series([1.5, 3, 6], idx)]
1889+
result = DataFrame(data2)
1890+
1891+
sdict = dict(zip(['x', 'Unnamed 0'], data))
1892+
expected = DataFrame.from_dict(sdict, orient='index')
1893+
assert_frame_equal(result.sort_index(), expected)
1894+
1895+
# none named
18741896
data = [{'a': 1.5, 'b': 3, 'c':4, 'd':6},
18751897
{'a': 1.5, 'b': 3, 'd':6},
18761898
{'a': 1.5, 'd':6},

0 commit comments

Comments
 (0)