Skip to content

Commit c42ed14

Browse files
committed
Clean imports in frame/test_apply.py
1 parent e903579 commit c42ed14

File tree

1 file changed

+84
-82
lines changed

1 file changed

+84
-82
lines changed

pandas/tests/frame/test_apply.py

Lines changed: 84 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@
1414
from hypothesis import given
1515
from hypothesis.strategies import composite, dates, integers, sampled_from
1616

17-
from pandas import (notna, DataFrame, Series, MultiIndex, date_range,
18-
Timestamp, compat)
19-
import pandas as pd
17+
from pandas import compat
18+
from pandas import (DataFrame, Series, Index, MultiIndex, DatetimeIndex,
19+
Timestamp, Timedelta, Period, date_range, to_datetime,
20+
to_timedelta, NaT, concat, notna)
21+
2022
from pandas.core.dtypes.dtypes import CategoricalDtype
2123
from pandas.core.apply import frame_apply
2224
from pandas.util.testing import (assert_series_equal,
@@ -72,7 +74,7 @@ def test_apply_mixed_datetimelike(self):
7274
# mixed datetimelike
7375
# GH 7778
7476
df = DataFrame({'A': date_range('20130101', periods=3),
75-
'B': pd.to_timedelta(np.arange(3), unit='s')})
77+
'B': to_timedelta(np.arange(3), unit='s')})
7678
result = df.apply(lambda x: x, axis=1)
7779
assert_frame_equal(result, df)
7880

@@ -106,14 +108,14 @@ def test_apply_with_reduce_empty(self, empty_frame):
106108
assert_frame_equal(result, empty_frame)
107109
result = empty_frame.apply(x.append, axis=1, result_type='reduce')
108110
assert_series_equal(result, Series(
109-
[], index=pd.Index([], dtype=object)))
111+
[], index=Index([], dtype=object)))
110112

111113
empty_with_cols = DataFrame(columns=['a', 'b', 'c'])
112114
result = empty_with_cols.apply(x.append, axis=1, result_type='expand')
113115
assert_frame_equal(result, empty_with_cols)
114116
result = empty_with_cols.apply(x.append, axis=1, result_type='reduce')
115117
assert_series_equal(result, Series(
116-
[], index=pd.Index([], dtype=object)))
118+
[], index=Index([], dtype=object)))
117119

118120
# Ensure that x.append hasn't been called
119121
assert x == []
@@ -241,7 +243,7 @@ def test_apply_mixed_dtype_corner(self):
241243
result = df[:0].apply(np.mean, axis=1)
242244
# the result here is actually kind of ambiguous, should it be a Series
243245
# or a DataFrame?
244-
expected = Series(np.nan, index=pd.Index([], dtype='int64'))
246+
expected = Series(np.nan, index=Index([], dtype='int64'))
245247
assert_series_equal(result, expected)
246248

247249
df = DataFrame({'A': ['foo'],
@@ -371,10 +373,10 @@ def transform2(row):
371373
def test_apply_bug(self):
372374

373375
# GH 6125
374-
positions = pd.DataFrame([[1, 'ABC0', 50], [1, 'YUM0', 20],
375-
[1, 'DEF0', 20], [2, 'ABC1', 50],
376-
[2, 'YUM1', 20], [2, 'DEF1', 20]],
377-
columns=['a', 'market', 'position'])
376+
positions = DataFrame([[1, 'ABC0', 50], [1, 'YUM0', 20],
377+
[1, 'DEF0', 20], [2, 'ABC1', 50],
378+
[2, 'YUM1', 20], [2, 'DEF1', 20]],
379+
columns=['a', 'market', 'position'])
378380

379381
def f(r):
380382
return r['market']
@@ -493,47 +495,47 @@ def test_applymap(self, float_frame):
493495

494496
# datetime/timedelta
495497
df['datetime'] = Timestamp('20130101')
496-
df['timedelta'] = pd.Timedelta('1 min')
498+
df['timedelta'] = Timedelta('1 min')
497499
result = df.applymap(str)
498500
for f in ['datetime', 'timedelta']:
499501
assert result.loc[0, f] == str(df.loc[0, f])
500502

501503
# see gh-8222
502-
empty_frames = [pd.DataFrame(),
503-
pd.DataFrame(columns=list('ABC')),
504-
pd.DataFrame(index=list('ABC')),
505-
pd.DataFrame({'A': [], 'B': [], 'C': []})]
504+
empty_frames = [DataFrame(),
505+
DataFrame(columns=list('ABC')),
506+
DataFrame(index=list('ABC')),
507+
DataFrame({'A': [], 'B': [], 'C': []})]
506508
for frame in empty_frames:
507509
for func in [round, lambda x: x]:
508510
result = frame.applymap(func)
509511
tm.assert_frame_equal(result, frame)
510512

511513
def test_applymap_box_timestamps(self):
512514
# #2689, #2627
513-
ser = pd.Series(date_range('1/1/2000', periods=10))
515+
ser = Series(date_range('1/1/2000', periods=10))
514516

515517
def func(x):
516518
return (x.hour, x.day, x.month)
517519

518520
# it works!
519-
pd.DataFrame(ser).applymap(func)
521+
DataFrame(ser).applymap(func)
520522

521523
def test_applymap_box(self):
522524
# ufunc will not be boxed. Same test cases as the test_map_box
523-
df = pd.DataFrame({'a': [pd.Timestamp('2011-01-01'),
524-
pd.Timestamp('2011-01-02')],
525-
'b': [pd.Timestamp('2011-01-01', tz='US/Eastern'),
526-
pd.Timestamp('2011-01-02', tz='US/Eastern')],
527-
'c': [pd.Timedelta('1 days'),
528-
pd.Timedelta('2 days')],
529-
'd': [pd.Period('2011-01-01', freq='M'),
530-
pd.Period('2011-01-02', freq='M')]})
525+
df = DataFrame({'a': [Timestamp('2011-01-01'),
526+
Timestamp('2011-01-02')],
527+
'b': [Timestamp('2011-01-01', tz='US/Eastern'),
528+
Timestamp('2011-01-02', tz='US/Eastern')],
529+
'c': [Timedelta('1 days'),
530+
Timedelta('2 days')],
531+
'd': [Period('2011-01-01', freq='M'),
532+
Period('2011-01-02', freq='M')]})
531533

532534
res = df.applymap(lambda x: '{0}'.format(x.__class__.__name__))
533-
exp = pd.DataFrame({'a': ['Timestamp', 'Timestamp'],
534-
'b': ['Timestamp', 'Timestamp'],
535-
'c': ['Timedelta', 'Timedelta'],
536-
'd': ['Period', 'Period']})
535+
exp = DataFrame({'a': ['Timestamp', 'Timestamp'],
536+
'b': ['Timestamp', 'Timestamp'],
537+
'c': ['Timedelta', 'Timedelta'],
538+
'd': ['Period', 'Period']})
537539
tm.assert_frame_equal(res, exp)
538540

539541
def test_frame_apply_dont_convert_datetime64(self):
@@ -547,14 +549,14 @@ def test_frame_apply_dont_convert_datetime64(self):
547549

548550
def test_apply_non_numpy_dtype(self):
549551
# See gh-12244
550-
df = DataFrame({'dt': pd.date_range(
552+
df = DataFrame({'dt': date_range(
551553
"2015-01-01", periods=3, tz='Europe/Brussels')})
552554
result = df.apply(lambda x: x)
553555
assert_frame_equal(result, df)
554556

555-
result = df.apply(lambda x: x + pd.Timedelta('1day'))
556-
expected = DataFrame({'dt': pd.date_range(
557-
"2015-01-02", periods=3, tz='Europe/Brussels')})
557+
result = df.apply(lambda x: x + Timedelta('1day'))
558+
expected = DataFrame({'dt': date_range("2015-01-02", periods=3,
559+
tz='Europe/Brussels')})
558560
assert_frame_equal(result, expected)
559561

560562
df = DataFrame({'dt': ['a', 'b', 'c', 'a']}, dtype='category')
@@ -563,8 +565,8 @@ def test_apply_non_numpy_dtype(self):
563565

564566
def test_apply_dup_names_multi_agg(self):
565567
# GH 21063
566-
df = pd.DataFrame([[0, 1], [2, 3]], columns=['a', 'a'])
567-
expected = pd.DataFrame([[0, 1]], columns=['a', 'a'], index=['min'])
568+
df = DataFrame([[0, 1], [2, 3]], columns=['a', 'a'])
569+
expected = DataFrame([[0, 1]], columns=['a', 'a'], index=['min'])
568570
result = df.agg(['min'])
569571

570572
tm.assert_frame_equal(result, expected)
@@ -578,7 +580,7 @@ class TestInferOutputShape(object):
578580
def test_infer_row_shape(self):
579581
# gh-17437
580582
# if row shape is changing, infer it
581-
df = pd.DataFrame(np.random.rand(10, 2))
583+
df = DataFrame(np.random.rand(10, 2))
582584
result = df.apply(np.fft.fft, axis=0)
583585
assert result.shape == (10, 2)
584586

@@ -593,8 +595,8 @@ def test_with_dictlike_columns(self):
593595
expected = Series([{'s': 3} for t in df.itertuples()])
594596
assert_series_equal(result, expected)
595597

596-
df['tm'] = [pd.Timestamp('2017-05-01 00:00:00'),
597-
pd.Timestamp('2017-05-02 00:00:00')]
598+
df['tm'] = [Timestamp('2017-05-01 00:00:00'),
599+
Timestamp('2017-05-02 00:00:00')]
598600
result = df.apply(lambda x: {'s': x['a'] + x['b']},
599601
axis=1)
600602
assert_series_equal(result, expected)
@@ -608,9 +610,9 @@ def test_with_dictlike_columns(self):
608610
df = DataFrame()
609611
df["author"] = ["X", "Y", "Z"]
610612
df["publisher"] = ["BBC", "NBC", "N24"]
611-
df["date"] = pd.to_datetime(['17-10-2010 07:15:30',
612-
'13-05-2011 08:20:35',
613-
'15-01-2013 09:09:09'])
613+
df["date"] = to_datetime(['17-10-2010 07:15:30',
614+
'13-05-2011 08:20:35',
615+
'15-01-2013 09:09:09'])
614616
result = df.apply(lambda x: {}, axis=1)
615617
expected = Series([{}, {}, {}])
616618
assert_series_equal(result, expected)
@@ -623,8 +625,8 @@ def test_with_dictlike_columns_with_infer(self):
623625
expected = DataFrame({'s': [3, 3]})
624626
assert_frame_equal(result, expected)
625627

626-
df['tm'] = [pd.Timestamp('2017-05-01 00:00:00'),
627-
pd.Timestamp('2017-05-02 00:00:00')]
628+
df['tm'] = [Timestamp('2017-05-01 00:00:00'),
629+
Timestamp('2017-05-02 00:00:00')]
628630
result = df.apply(lambda x: {'s': x['a'] + x['b']},
629631
axis=1, result_type='expand')
630632
assert_frame_equal(result, expected)
@@ -659,8 +661,8 @@ def test_infer_output_shape_columns(self):
659661

660662
df = DataFrame({'number': [1., 2.],
661663
'string': ['foo', 'bar'],
662-
'datetime': [pd.Timestamp('2017-11-29 03:30:00'),
663-
pd.Timestamp('2017-11-29 03:45:00')]})
664+
'datetime': [Timestamp('2017-11-29 03:30:00'),
665+
Timestamp('2017-11-29 03:45:00')]})
664666
result = df.apply(lambda row: (row.number, row.string), axis=1)
665667
expected = Series([(t.number, t.string) for t in df.itertuples()])
666668
assert_series_equal(result, expected)
@@ -692,13 +694,13 @@ def test_infer_output_shape_listlike_columns(self):
692694
assert_series_equal(result, expected)
693695

694696
# gh-17892
695-
df = pd.DataFrame({'a': [pd.Timestamp('2010-02-01'),
696-
pd.Timestamp('2010-02-04'),
697-
pd.Timestamp('2010-02-05'),
698-
pd.Timestamp('2010-02-06')],
699-
'b': [9, 5, 4, 3],
700-
'c': [5, 3, 4, 2],
701-
'd': [1, 2, 3, 4]})
697+
df = DataFrame({'a': [Timestamp('2010-02-01'),
698+
Timestamp('2010-02-04'),
699+
Timestamp('2010-02-05'),
700+
Timestamp('2010-02-06')],
701+
'b': [9, 5, 4, 3],
702+
'c': [5, 3, 4, 2],
703+
'd': [1, 2, 3, 4]})
702704

703705
def fun(x):
704706
return (1, 2)
@@ -815,11 +817,11 @@ def zip_frames(frames, axis=1):
815817
if axis == 1:
816818
columns = frames[0].columns
817819
zipped = [f.loc[:, c] for c in columns for f in frames]
818-
return pd.concat(zipped, axis=1)
820+
return concat(zipped, axis=1)
819821
else:
820822
index = frames[0].index
821823
zipped = [f.loc[i, :] for i in index for f in frames]
822-
return pd.DataFrame(zipped)
824+
return DataFrame(zipped)
823825

824826

825827
class TestDataFrameAggregate():
@@ -847,10 +849,10 @@ def test_agg_transform(self, axis, float_frame):
847849
result = float_frame.apply([np.sqrt], axis=axis)
848850
expected = f_sqrt.copy()
849851
if axis in {0, 'index'}:
850-
expected.columns = pd.MultiIndex.from_product(
852+
expected.columns = MultiIndex.from_product(
851853
[float_frame.columns, ['sqrt']])
852854
else:
853-
expected.index = pd.MultiIndex.from_product(
855+
expected.index = MultiIndex.from_product(
854856
[float_frame.index, ['sqrt']])
855857
assert_frame_equal(result, expected)
856858

@@ -863,10 +865,10 @@ def test_agg_transform(self, axis, float_frame):
863865
result = float_frame.apply([np.abs, np.sqrt], axis=axis)
864866
expected = zip_frames([f_abs, f_sqrt], axis=other_axis)
865867
if axis in {0, 'index'}:
866-
expected.columns = pd.MultiIndex.from_product(
868+
expected.columns = MultiIndex.from_product(
867869
[float_frame.columns, ['absolute', 'sqrt']])
868870
else:
869-
expected.index = pd.MultiIndex.from_product(
871+
expected.index = MultiIndex.from_product(
870872
[float_frame.index, ['absolute', 'sqrt']])
871873
assert_frame_equal(result, expected)
872874

@@ -889,7 +891,7 @@ def f():
889891
float_frame.transform(['max', 'sqrt'], axis=axis)
890892
pytest.raises(ValueError, f)
891893

892-
df = pd.DataFrame({'A': range(5), 'B': 5})
894+
df = DataFrame({'A': range(5), 'B': 5})
893895

894896
def f():
895897
with np.errstate(all='ignore'):
@@ -900,14 +902,14 @@ def f():
900902
])
901903
def test_transform_method_name(self, method):
902904
# https://github.com/pandas-dev/pandas/issues/19760
903-
df = pd.DataFrame({"A": [-1, 2]})
905+
df = DataFrame({"A": [-1, 2]})
904906
result = df.transform(method)
905907
expected = operator.methodcaller(method)(df)
906908
tm.assert_frame_equal(result, expected)
907909

908910
def test_demo(self):
909911
# demonstration tests
910-
df = pd.DataFrame({'A': range(5), 'B': 5})
912+
df = DataFrame({'A': range(5), 'B': 5})
911913

912914
result = df.agg(['min', 'max'])
913915
expected = DataFrame({'A': [0, 4], 'B': [5, 5]},
@@ -924,14 +926,14 @@ def test_demo(self):
924926

925927
def test_agg_multiple_mixed_no_warning(self):
926928
# https://github.com/pandas-dev/pandas/issues/20909
927-
mdf = pd.DataFrame({'A': [1, 2, 3],
928-
'B': [1., 2., 3.],
929-
'C': ['foo', 'bar', 'baz'],
930-
'D': pd.date_range('20130101', periods=3)})
931-
expected = pd.DataFrame({"A": [1, 6], 'B': [1.0, 6.0],
932-
"C": ['bar', 'foobarbaz'],
933-
"D": [pd.Timestamp('2013-01-01'), pd.NaT]},
934-
index=['min', 'sum'])
929+
mdf = DataFrame({'A': [1, 2, 3],
930+
'B': [1., 2., 3.],
931+
'C': ['foo', 'bar', 'baz'],
932+
'D': date_range('20130101', periods=3)})
933+
expected = DataFrame({'A': [1, 6], 'B': [1.0, 6.0],
934+
'C': ['bar', 'foobarbaz'],
935+
'D': [Timestamp('2013-01-01'), NaT]},
936+
index=['min', 'sum'])
935937
# sorted index
936938
with tm.assert_produces_warning(None):
937939
result = mdf.agg(['min', 'sum'])
@@ -949,7 +951,7 @@ def test_agg_multiple_mixed_no_warning(self):
949951

950952
def test_agg_dict_nested_renaming_depr(self):
951953

952-
df = pd.DataFrame({'A': range(5), 'B': 5})
954+
df = DataFrame({'A': range(5), 'B': 5})
953955

954956
# nested renaming
955957
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
@@ -961,10 +963,10 @@ def test_agg_reduce(self, axis, float_frame):
961963
name1, name2 = float_frame.axes[other_axis].unique()[:2].sort_values()
962964

963965
# all reducers
964-
expected = pd.concat([float_frame.mean(axis=axis),
965-
float_frame.max(axis=axis),
966-
float_frame.sum(axis=axis),
967-
], axis=1)
966+
expected = concat([float_frame.mean(axis=axis),
967+
float_frame.max(axis=axis),
968+
float_frame.sum(axis=axis),
969+
], axis=1)
968970
expected.columns = ['mean', 'max', 'sum']
969971
expected = expected.T if axis in {0, 'index'} else expected
970972

@@ -1010,15 +1012,15 @@ def test_nuiscance_columns(self):
10101012
df = DataFrame({'A': [1, 2, 3],
10111013
'B': [1., 2., 3.],
10121014
'C': ['foo', 'bar', 'baz'],
1013-
'D': pd.date_range('20130101', periods=3)})
1015+
'D': date_range('20130101', periods=3)})
10141016

10151017
result = df.agg('min')
1016-
expected = Series([1, 1., 'bar', pd.Timestamp('20130101')],
1018+
expected = Series([1, 1., 'bar', Timestamp('20130101')],
10171019
index=df.columns)
10181020
assert_series_equal(result, expected)
10191021

10201022
result = df.agg(['min'])
1021-
expected = DataFrame([[1, 1., 'bar', pd.Timestamp('20130101')]],
1023+
expected = DataFrame([[1, 1., 'bar', Timestamp('20130101')]],
10221024
index=['min'], columns=df.columns)
10231025
assert_frame_equal(result, expected)
10241026

@@ -1058,9 +1060,9 @@ def test_non_callable_aggregates(self):
10581060
result2 = df.agg({'A': ['count', 'size'],
10591061
'B': ['count', 'size'],
10601062
'C': ['count', 'size']})
1061-
expected = pd.DataFrame({'A': {'count': 2, 'size': 3},
1062-
'B': {'count': 2, 'size': 3},
1063-
'C': {'count': 2, 'size': 3}})
1063+
expected = DataFrame({'A': {'count': 2, 'size': 3},
1064+
'B': {'count': 2, 'size': 3},
1065+
'C': {'count': 2, 'size': 3}})
10641066

10651067
assert_frame_equal(result1, result2, check_like=True)
10661068
assert_frame_equal(result2, expected, check_like=True)
@@ -1152,7 +1154,7 @@ def indices(draw, max_length=5):
11521154
periods = draw(integers(0, max_length))
11531155
freq = draw(sampled_from(list("BDHTS")))
11541156
dr = date_range(date, periods=periods, freq=freq)
1155-
return pd.DatetimeIndex(list(dr))
1157+
return DatetimeIndex(list(dr))
11561158

11571159
@given(index=indices(5), num_columns=integers(0, 5))
11581160
def test_frequency_is_original(self, index, num_columns):

0 commit comments

Comments
 (0)