Skip to content

Commit dfe7a55

Browse files
committed
BUG: set index name/names in DataFrame.from_records. close #1744
1 parent 428de74 commit dfe7a55

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

RELEASE.rst

+2
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ pandas 0.9.0
192192
- Various fixes by upcasting of date -> datetime (#1395)
193193
- Raise better exception when passing multiple functions with the same name,
194194
such as lambdas, to GroupBy.aggregate
195+
- Fix DataFrame.apply with axis=1 on a non-unique index (#1878)
196+
- Proper handling of Index subclasses in pandas.unique (#1759)
195197

196198
pandas 0.8.1
197199
============

pandas/core/frame.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -856,6 +856,7 @@ def from_records(cls, data, index=None, exclude=None, columns=None,
856856
if (isinstance(index, basestring) or
857857
not hasattr(index, "__iter__")):
858858
result_index = sdict.pop(index)
859+
result_index = Index(result_index, name=index)
859860
columns.remove(index)
860861
else:
861862
try:
@@ -865,7 +866,7 @@ def from_records(cls, data, index=None, exclude=None, columns=None,
865866
for field in index:
866867
del sdict[field]
867868
columns.remove(field)
868-
result_index = MultiIndex.from_arrays(arrays)
869+
result_index = MultiIndex.from_arrays(arrays, names=index)
869870
except Exception:
870871
result_index = index
871872
elif isinstance(data, dict) and len(data) > 0:

pandas/tests/test_frame.py

+16
Original file line numberDiff line numberDiff line change
@@ -2448,6 +2448,22 @@ def test_from_records_duplicates(self):
24482448
self.assertRaises(ValueError, DataFrame.from_records,
24492449
[(1,2,3), (4,5,6)], columns=['a','b','a'])
24502450

2451+
def test_from_records_set_index_name(self):
2452+
def create_dict(order_id):
2453+
return {'order_id': order_id, 'quantity': np.random.randint(1, 10),
2454+
'price': np.random.randint(1, 10)}
2455+
documents = [create_dict(i) for i in range(10)]
2456+
# demo missing data
2457+
documents.append({'order_id': 10, 'quantity': 5})
2458+
2459+
result = DataFrame.from_records(documents, index='order_id')
2460+
self.assert_(result.index.name == 'order_id')
2461+
2462+
# MultiIndex
2463+
result = DataFrame.from_records(documents,
2464+
index=['order_id', 'quantity'])
2465+
self.assert_(result.index.names == ['order_id', 'quantity'])
2466+
24512467
def test_to_records_floats(self):
24522468
df = DataFrame(np.random.rand(10,10))
24532469
df.to_records()

0 commit comments

Comments
 (0)