Skip to content

Commit 56d45fa

Browse files
committed
Support a column_name arg to read_frame to override column names.
1 parent 0db4897 commit 56d45fa

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

README.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ read_frame
125125
human readable versions of any foreign key or choice fields
126126
else use the actual values set in the model.
127127

128+
- column_names: If not None, use to override the column names in the
129+
DateFrame
128130

129131
Examples
130132
^^^^^^^^^

django_pandas/io.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def is_values_queryset(qs):
3333

3434

3535
def read_frame(qs, fieldnames=(), index_col=None, coerce_float=False,
36-
verbose=True, datetime_index=False):
36+
verbose=True, datetime_index=False, column_names=None):
3737
"""
3838
Returns a dataframe from a QuerySet
3939
@@ -68,13 +68,18 @@ def read_frame(qs, fieldnames=(), index_col=None, coerce_float=False,
6868
6969
datetime_index: specify whether index should be converted to a
7070
DateTimeIndex.
71+
72+
column_names: If not None, use to override the column names in the
73+
DateFrame
7174
"""
7275

7376
if fieldnames:
7477
fieldnames = pd.unique(fieldnames)
7578
if index_col is not None and index_col not in fieldnames:
7679
# Add it to the field names if not already there
7780
fieldnames = tuple(fieldnames) + (index_col,)
81+
if column_names:
82+
column_names = tuple(column_names) + (index_col,)
7883
fields = to_fields(qs, fieldnames)
7984
elif is_values_queryset(qs):
8085
if django.VERSION < (1, 9): # pragma: no cover
@@ -114,8 +119,11 @@ def read_frame(qs, fieldnames=(), index_col=None, coerce_float=False,
114119
else:
115120
recs = list(qs.values_list(*fieldnames))
116121

117-
df = pd.DataFrame.from_records(recs, columns=fieldnames,
118-
coerce_float=coerce_float)
122+
df = pd.DataFrame.from_records(
123+
recs,
124+
columns=column_names if column_names else fieldnames,
125+
coerce_float=coerce_float
126+
)
119127

120128
if verbose:
121129
update_with_verbose(df, fieldnames, fields)

django_pandas/tests/test_io.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,16 @@ def test_values(self):
5757
['index_col', 'col1', 'scol1', 'ecol1'])
5858
self.assertEqual(list(df["col1"]), list(df["scol1"]))
5959

60+
def test_override_column_names(self):
61+
qs = MyModel.objects.all()
62+
df = read_frame(
63+
qs,
64+
index_col='id',
65+
fieldnames=['col1', 'col2', 'col3', 'col4'],
66+
column_names=['a', 'b', 'c', 'd']
67+
)
68+
self.assertEqual(list(df.columns), ['a', 'b', 'c', 'd'])
69+
6070
def test_duplicate_annotation(self):
6171
qs = MyModel.objects.all()
6272
qs = qs.values('index_col')

0 commit comments

Comments
 (0)