Skip to content

TST: Check index names #9972

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 28, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions pandas/io/tests/test_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def test_squeeze(self):
b,2
c,3
"""
expected = Series([1, 2, 3], ['a', 'b', 'c'])
expected = Series([1, 2, 3], index=Index(['a', 'b', 'c'], name=0))
result = self.read_table(StringIO(data), sep=',', index_col=0,
header=None, squeeze=True)
tm.assert_isinstance(result, Series)
Expand Down Expand Up @@ -981,17 +981,17 @@ def test_yy_format(self):
parse_dates=[['date', 'time']])
idx = DatetimeIndex([datetime(2009, 1, 31, 0, 10, 0),
datetime(2009, 2, 28, 10, 20, 0),
datetime(2009, 3, 31, 8, 30, 0)]).asobject
idx.name = 'date_time'
datetime(2009, 3, 31, 8, 30, 0)],
dtype=object, name='date_time')
xp = DataFrame({'B': [1, 3, 5], 'C': [2, 4, 6]}, idx)
tm.assert_frame_equal(rs, xp)

rs = self.read_csv(StringIO(data), index_col=0,
parse_dates=[[0, 1]])
idx = DatetimeIndex([datetime(2009, 1, 31, 0, 10, 0),
datetime(2009, 2, 28, 10, 20, 0),
datetime(2009, 3, 31, 8, 30, 0)]).asobject
idx.name = 'date_time'
datetime(2009, 3, 31, 8, 30, 0)],
dtype=object, name='date_time')
xp = DataFrame({'B': [1, 3, 5], 'C': [2, 4, 6]}, idx)
tm.assert_frame_equal(rs, xp)

Expand Down Expand Up @@ -3110,17 +3110,17 @@ def test_skiprows_lineterminator(self):
expected = pd.DataFrame([['2007/01/01', '01:00', 0.2140, 'U', 'M'],
['2007/01/01', '02:00', 0.2141, 'M', 'O'],
['2007/01/01', '04:00', 0.2142, 'D', 'M']],
columns=['date', 'time', 'var', 'flag',
columns=['date', 'time', 'var', 'flag',
'oflag'])
# test with the three default lineterminators LF, CR and CRLF
df = self.read_csv(StringIO(data), skiprows=1, delim_whitespace=True,
names=['date', 'time', 'var', 'flag', 'oflag'])
tm.assert_frame_equal(df, expected)
df = self.read_csv(StringIO(data.replace('\n', '\r')),
df = self.read_csv(StringIO(data.replace('\n', '\r')),
skiprows=1, delim_whitespace=True,
names=['date', 'time', 'var', 'flag', 'oflag'])
tm.assert_frame_equal(df, expected)
df = self.read_csv(StringIO(data.replace('\n', '\r\n')),
df = self.read_csv(StringIO(data.replace('\n', '\r\n')),
skiprows=1, delim_whitespace=True,
names=['date', 'time', 'var', 'flag', 'oflag'])
tm.assert_frame_equal(df, expected)
Expand Down
5 changes: 3 additions & 2 deletions pandas/io/tests/test_pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1593,9 +1593,10 @@ def make_index(names=None):

# series
_maybe_remove(store, 's')
s = Series(np.zeros(12), index=make_index(['date',None,None]))
s = Series(np.zeros(12), index=make_index(['date', None, None]))
store.append('s',s)
tm.assert_series_equal(store.select('s'),s)
xp = Series(np.zeros(12), index=make_index(['date', 'level_1', 'level_2']))
tm.assert_series_equal(store.select('s'), xp)

# dup with column
_maybe_remove(store, 'df')
Expand Down
20 changes: 10 additions & 10 deletions pandas/io/tests/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -1323,19 +1323,19 @@ def test_double_precision(self):
'i64':Series([5,], dtype='int64'),
})

df.to_sql('test_dtypes', self.conn, index=False, if_exists='replace',
df.to_sql('test_dtypes', self.conn, index=False, if_exists='replace',
dtype={'f64_as_f32':sqlalchemy.Float(precision=23)})
res = sql.read_sql_table('test_dtypes', self.conn)

# check precision of float64
self.assertEqual(np.round(df['f64'].iloc[0],14),
self.assertEqual(np.round(df['f64'].iloc[0],14),
np.round(res['f64'].iloc[0],14))

# check sql types
meta = sqlalchemy.schema.MetaData(bind=self.conn)
meta.reflect()
col_dict = meta.tables['test_dtypes'].columns
self.assertEqual(str(col_dict['f32'].type),
self.assertEqual(str(col_dict['f32'].type),
str(col_dict['f64_as_f32'].type))
self.assertTrue(isinstance(col_dict['f32'].type, sqltypes.Float))
self.assertTrue(isinstance(col_dict['f64'].type, sqltypes.Float))
Expand Down Expand Up @@ -1729,11 +1729,11 @@ def test_illegal_names(self):
df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])

# Raise error on blank
self.assertRaises(ValueError, df.to_sql, "", self.conn,
self.assertRaises(ValueError, df.to_sql, "", self.conn,
flavor=self.flavor)

for ndx, weird_name in enumerate(['test_weird_name]','test_weird_name[',
'test_weird_name`','test_weird_name"', 'test_weird_name\'',
'test_weird_name`','test_weird_name"', 'test_weird_name\'',
'_b.test_weird_name_01-30', '"_b.test_weird_name_01-30"']):
df.to_sql(weird_name, self.conn, flavor=self.flavor)
sql.table_exists(weird_name, self.conn)
Expand Down Expand Up @@ -1839,12 +1839,12 @@ def test_illegal_names(self):
for ndx, illegal_name in enumerate(['test_illegal_name]','test_illegal_name[',
'test_illegal_name`','test_illegal_name"', 'test_illegal_name\'', '']):
df = DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
self.assertRaises(ValueError, df.to_sql, illegal_name, self.conn,
self.assertRaises(ValueError, df.to_sql, illegal_name, self.conn,
flavor=self.flavor, index=False)

df2 = DataFrame([[1, 2], [3, 4]], columns=['a', illegal_name])
c_tbl = 'test_illegal_col_name%d'%ndx
self.assertRaises(ValueError, df2.to_sql, 'test_illegal_col_name',
self.assertRaises(ValueError, df2.to_sql, 'test_illegal_col_name',
self.conn, flavor=self.flavor, index=False)


Expand Down Expand Up @@ -2021,7 +2021,7 @@ def test_tquery(self):
frame = tm.makeTimeDataFrame()
sql.write_frame(frame, name='test_table', con=self.db)
result = sql.tquery("select A from test_table", self.db)
expected = frame.A
expected = Series(frame.A, frame.index) # not to have name
result = Series(result, frame.index)
tm.assert_series_equal(result, expected)

Expand Down Expand Up @@ -2359,7 +2359,7 @@ def test_tquery(self):
cur.execute(drop_sql)
sql.write_frame(frame, name='test_table', con=self.db, flavor='mysql')
result = sql.tquery("select A from test_table", self.db)
expected = frame.A
expected = Series(frame.A, frame.index) # not to have name
result = Series(result, frame.index)
tm.assert_series_equal(result, expected)

Expand Down
4 changes: 2 additions & 2 deletions pandas/io/tests/test_stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,8 +875,8 @@ def test_categorical_sorting(self):
parsed_117.index = np.arange(parsed_117.shape[0])
codes = [-1, -1, 0, 1, 1, 1, 2, 2, 3, 4]
categories = ["Poor", "Fair", "Good", "Very good", "Excellent"]
expected = pd.Series(pd.Categorical.from_codes(codes=codes,
categories=categories))
cat = pd.Categorical.from_codes(codes=codes, categories=categories)
expected = pd.Series(cat, name='srh')
tm.assert_series_equal(expected, parsed_115["srh"])
tm.assert_series_equal(expected, parsed_117["srh"])

Expand Down
14 changes: 8 additions & 6 deletions pandas/sparse/tests/test_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import pandas.tests.test_panel as test_panel
import pandas.tests.test_series as test_series

from .test_array import assert_sp_array_equal
from pandas.sparse.tests.test_array import assert_sp_array_equal

import warnings
warnings.filterwarnings(action='ignore', category=FutureWarning)
Expand Down Expand Up @@ -281,7 +281,7 @@ def test_constructor_nonnan(self):
arr = [0, 0, 0, nan, nan]
sp_series = SparseSeries(arr, fill_value=0)
assert_equal(sp_series.values.values, arr)

# GH 9272
def test_constructor_empty(self):
sp = SparseSeries()
Expand Down Expand Up @@ -997,7 +997,7 @@ def test_constructor_ndarray(self):
ValueError, "^Column length", SparseDataFrame, self.frame.values,
columns=self.frame.columns[:-1])

# GH 9272
# GH 9272
def test_constructor_empty(self):
sp = SparseDataFrame()
self.assertEqual(len(sp.index), 0)
Expand Down Expand Up @@ -1283,7 +1283,9 @@ def _check_frame(frame):
frame['E'] = to_insert
expected = to_insert.to_dense().reindex(
frame.index).fillna(to_insert.fill_value)
assert_series_equal(frame['E'].to_dense(), expected)
result = frame['E'].to_dense()
assert_series_equal(result, expected, check_names=False)
self.assertEqual(result.name, 'E')

# insert Series
frame['F'] = frame['A'].to_dense()
Expand Down Expand Up @@ -1747,8 +1749,8 @@ def test_constructor(self):
with tm.assertRaisesRegexp(TypeError,
"input must be a dict, a 'list' was passed"):
SparsePanel(['a', 'b', 'c'])
# GH 9272

# GH 9272
def test_constructor_empty(self):
sp = SparsePanel()
self.assertEqual(len(sp.items), 0)
Expand Down
3 changes: 2 additions & 1 deletion pandas/stats/tests/test_moments.py
Original file line number Diff line number Diff line change
Expand Up @@ -1254,7 +1254,8 @@ def _check_pairwise_moment(self, func, *args, **kwargs):

actual = panel.ix[:, 1, 5]
expected = func(self.frame[1], self.frame[5], *args, **kwargs)
tm.assert_series_equal(actual, expected)
tm.assert_series_equal(actual, expected, check_names=False)
self.assertEqual(actual.name, 5)

def test_flex_binary_moment(self):
# GH3155
Expand Down
20 changes: 12 additions & 8 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2395,22 +2395,26 @@ def test_construction_with_categorical_index(self):
'B' : ci.values })
idf = df.set_index('B')
str(idf)
tm.assert_index_equal(idf.index,ci)
tm.assert_index_equal(idf.index, ci, check_names=False)
self.assertEqual(idf.index.name, 'B')

# from a CategoricalIndex
df = DataFrame({'A' : np.random.randn(10),
'B' : ci })
idf = df.set_index('B')
str(idf)
tm.assert_index_equal(idf.index,ci)
tm.assert_index_equal(idf.index, ci, check_names=False)
self.assertEqual(idf.index.name, 'B')

idf = df.set_index('B').reset_index().set_index('B')
str(idf)
tm.assert_index_equal(idf.index,ci)
tm.assert_index_equal(idf.index, ci, check_names=False)
self.assertEqual(idf.index.name, 'B')

new_df = idf.reset_index()
new_df.index = df.B
tm.assert_index_equal(new_df.index,ci)
tm.assert_index_equal(new_df.index, ci, check_names=False)
self.assertEqual(idf.index.name, 'B')

def test_set_index_cast_datetimeindex(self):
df = DataFrame({'A': [datetime(2000, 1, 1) + timedelta(i)
Expand Down Expand Up @@ -7488,19 +7492,19 @@ def test_drop_names(self):

# errors = 'ignore'
dropped = df.drop(['g'], errors='ignore')
expected = Index(['a', 'b', 'c'])
expected = Index(['a', 'b', 'c'], name='first')
self.assert_index_equal(dropped.index, expected)

dropped = df.drop(['b', 'g'], errors='ignore')
expected = Index(['a', 'c'])
expected = Index(['a', 'c'], name='first')
self.assert_index_equal(dropped.index, expected)

dropped = df.drop(['g'], axis=1, errors='ignore')
expected = Index(['d', 'e', 'f'])
expected = Index(['d', 'e', 'f'], name='second')
self.assert_index_equal(dropped.columns, expected)

dropped = df.drop(['d', 'g'], axis=1, errors='ignore')
expected = Index(['e', 'f'])
expected = Index(['e', 'f'], name='second')
self.assert_index_equal(dropped.columns, expected)

def test_dropEmptyRows(self):
Expand Down
22 changes: 13 additions & 9 deletions pandas/tests/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,9 +297,9 @@ def test_nth(self):
# as it keeps the order in the series (and not the group order)
# related GH 7287
expected = s.groupby(g,sort=False).first()
expected.index = range(1,10)
result = s.groupby(g).nth(0,dropna='all')
assert_series_equal(result,expected)
expected.index = pd.Index(range(1,10), name=0)
result = s.groupby(g).nth(0, dropna='all')
assert_series_equal(result, expected)

# doc example
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
Expand Down Expand Up @@ -807,9 +807,10 @@ def test_apply_issues(self):
# GH 5789
# don't auto coerce dates
df = pd.read_csv(StringIO(s), header=None, names=['date', 'time', 'value'])
expected = Series(['00:00','02:00','02:00'],index=['2011.05.16','2011.05.17','2011.05.18'])
exp_idx = pd.Index(['2011.05.16','2011.05.17','2011.05.18'], dtype=object, name='date')
expected = Series(['00:00','02:00','02:00'], index=exp_idx)
result = df.groupby('date').apply(lambda x: x['time'][x['value'].idxmax()])
assert_series_equal(result,expected)
assert_series_equal(result, expected)

def test_len(self):
df = tm.makeTimeDataFrame()
Expand Down Expand Up @@ -1700,7 +1701,8 @@ def test_groupby_as_index_apply(self):
# apply doesn't maintain the original ordering
# changed in GH5610 as the as_index=False returns a MI here
exp_not_as_apply = MultiIndex.from_tuples([(0, 0), (0, 2), (1, 1), (2, 4)])
exp_as_apply = MultiIndex.from_tuples([(1, 0), (1, 2), (2, 1), (3, 4)])
tp = [(1, 0), (1, 2), (2, 1), (3, 4)]
exp_as_apply = MultiIndex.from_tuples(tp, names=['user_id', None])

assert_index_equal(res_as_apply, exp_as_apply)
assert_index_equal(res_not_as_apply, exp_not_as_apply)
Expand Down Expand Up @@ -1922,6 +1924,8 @@ def _testit(op):
for (cat1, cat2), group in grouped:
expd.setdefault(cat1, {})[cat2] = op(group['C'])
exp = DataFrame(expd).T.stack(dropna=False)
exp.index.names = ['A', 'B']

result = op(grouped)['C']
assert_series_equal(result, exp)

Expand Down Expand Up @@ -1974,7 +1978,7 @@ def test_cython_agg_nothing_to_agg_with_dates(self):
def test_groupby_timedelta_cython_count(self):
df = DataFrame({'g': list('ab' * 2),
'delt': np.arange(4).astype('timedelta64[ns]')})
expected = Series([2, 2], index=['a', 'b'], name='delt')
expected = Series([2, 2], index=pd.Index(['a', 'b'], name='g'), name='delt')
result = df.groupby('g').delt.count()
tm.assert_series_equal(expected, result)

Expand Down Expand Up @@ -2385,13 +2389,13 @@ def test_count_object(self):
df = pd.DataFrame({'a': ['a'] * 3 + ['b'] * 3,
'c': [2] * 3 + [3] * 3})
result = df.groupby('c').a.count()
expected = pd.Series([3, 3], index=[2, 3], name='a')
expected = pd.Series([3, 3], index=pd.Index([2, 3], name='c'), name='a')
tm.assert_series_equal(result, expected)

df = pd.DataFrame({'a': ['a', np.nan, np.nan] + ['b'] * 3,
'c': [2] * 3 + [3] * 3})
result = df.groupby('c').a.count()
expected = pd.Series([1, 3], index=[2, 3], name='a')
expected = pd.Series([1, 3], index=pd.Index([2, 3], name='c'), name='a')
tm.assert_series_equal(result, expected)

def test_count_cross_type(self): # GH8169
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -2055,10 +2055,10 @@ def test_view(self):
self.assertEqual(i_view.name, 'Foo')

i_view = i.view('i8')
tm.assert_index_equal(i, Int64Index(i_view))
tm.assert_index_equal(i, Int64Index(i_view, name='Foo'))

i_view = i.view(Int64Index)
tm.assert_index_equal(i, Int64Index(i_view))
tm.assert_index_equal(i, Int64Index(i_view, name='Foo'))

def test_coerce_list(self):
# coerce things
Expand Down
Loading