test_scalar.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. """ test scalar indexing, including at and iat """
  2. import numpy as np
  3. import pytest
  4. from pandas import DataFrame, Series, Timedelta, Timestamp, date_range
  5. from pandas.tests.indexing.common import Base
  6. from pandas.util import testing as tm
  7. class TestScalar(Base):
  8. def test_at_and_iat_get(self):
  9. def _check(f, func, values=False):
  10. if f is not None:
  11. indicies = self.generate_indices(f, values)
  12. for i in indicies:
  13. result = getattr(f, func)[i]
  14. expected = self.get_value(f, i, values)
  15. tm.assert_almost_equal(result, expected)
  16. for o in self._objs:
  17. d = getattr(self, o)
  18. # iat
  19. for f in [d['ints'], d['uints']]:
  20. _check(f, 'iat', values=True)
  21. for f in [d['labels'], d['ts'], d['floats']]:
  22. if f is not None:
  23. pytest.raises(ValueError, self.check_values, f, 'iat')
  24. # at
  25. for f in [d['ints'], d['uints'], d['labels'],
  26. d['ts'], d['floats']]:
  27. _check(f, 'at')
  28. def test_at_and_iat_set(self):
  29. def _check(f, func, values=False):
  30. if f is not None:
  31. indicies = self.generate_indices(f, values)
  32. for i in indicies:
  33. getattr(f, func)[i] = 1
  34. expected = self.get_value(f, i, values)
  35. tm.assert_almost_equal(expected, 1)
  36. for t in self._objs:
  37. d = getattr(self, t)
  38. # iat
  39. for f in [d['ints'], d['uints']]:
  40. _check(f, 'iat', values=True)
  41. for f in [d['labels'], d['ts'], d['floats']]:
  42. if f is not None:
  43. pytest.raises(ValueError, _check, f, 'iat')
  44. # at
  45. for f in [d['ints'], d['uints'], d['labels'],
  46. d['ts'], d['floats']]:
  47. _check(f, 'at')
  48. def test_at_iat_coercion(self):
  49. # as timestamp is not a tuple!
  50. dates = date_range('1/1/2000', periods=8)
  51. df = DataFrame(np.random.randn(8, 4),
  52. index=dates,
  53. columns=['A', 'B', 'C', 'D'])
  54. s = df['A']
  55. result = s.at[dates[5]]
  56. xp = s.values[5]
  57. assert result == xp
  58. # GH 7729
  59. # make sure we are boxing the returns
  60. s = Series(['2014-01-01', '2014-02-02'], dtype='datetime64[ns]')
  61. expected = Timestamp('2014-02-02')
  62. for r in [lambda: s.iat[1], lambda: s.iloc[1]]:
  63. result = r()
  64. assert result == expected
  65. s = Series(['1 days', '2 days'], dtype='timedelta64[ns]')
  66. expected = Timedelta('2 days')
  67. for r in [lambda: s.iat[1], lambda: s.iloc[1]]:
  68. result = r()
  69. assert result == expected
  70. def test_iat_invalid_args(self):
  71. pass
  72. def test_imethods_with_dups(self):
  73. # GH6493
  74. # iat/iloc with dups
  75. s = Series(range(5), index=[1, 1, 2, 2, 3], dtype='int64')
  76. result = s.iloc[2]
  77. assert result == 2
  78. result = s.iat[2]
  79. assert result == 2
  80. pytest.raises(IndexError, lambda: s.iat[10])
  81. pytest.raises(IndexError, lambda: s.iat[-10])
  82. result = s.iloc[[2, 3]]
  83. expected = Series([2, 3], [2, 2], dtype='int64')
  84. tm.assert_series_equal(result, expected)
  85. df = s.to_frame()
  86. result = df.iloc[2]
  87. expected = Series(2, index=[0], name=2)
  88. tm.assert_series_equal(result, expected)
  89. result = df.iat[2, 0]
  90. assert result == 2
  91. def test_at_to_fail(self):
  92. # at should not fallback
  93. # GH 7814
  94. s = Series([1, 2, 3], index=list('abc'))
  95. result = s.at['a']
  96. assert result == 1
  97. pytest.raises(ValueError, lambda: s.at[0])
  98. df = DataFrame({'A': [1, 2, 3]}, index=list('abc'))
  99. result = df.at['a', 'A']
  100. assert result == 1
  101. pytest.raises(ValueError, lambda: df.at['a', 0])
  102. s = Series([1, 2, 3], index=[3, 2, 1])
  103. result = s.at[1]
  104. assert result == 3
  105. pytest.raises(ValueError, lambda: s.at['a'])
  106. df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1])
  107. result = df.at[1, 0]
  108. assert result == 3
  109. pytest.raises(ValueError, lambda: df.at['a', 0])
  110. # GH 13822, incorrect error string with non-unique columns when missing
  111. # column is accessed
  112. df = DataFrame({'x': [1.], 'y': [2.], 'z': [3.]})
  113. df.columns = ['x', 'x', 'z']
  114. # Check that we get the correct value in the KeyError
  115. with pytest.raises(KeyError, match=r"\['y'\] not in index"):
  116. df[['x', 'y', 'z']]
  117. def test_at_with_tz(self):
  118. # gh-15822
  119. df = DataFrame({'name': ['John', 'Anderson'],
  120. 'date': [Timestamp(2017, 3, 13, 13, 32, 56),
  121. Timestamp(2017, 2, 16, 12, 10, 3)]})
  122. df['date'] = df['date'].dt.tz_localize('Asia/Shanghai')
  123. expected = Timestamp('2017-03-13 13:32:56+0800', tz='Asia/Shanghai')
  124. result = df.loc[0, 'date']
  125. assert result == expected
  126. result = df.at[0, 'date']
  127. assert result == expected
  128. def test_mixed_index_at_iat_loc_iloc_series(self):
  129. # GH 19860
  130. s = Series([1, 2, 3, 4, 5], index=['a', 'b', 'c', 1, 2])
  131. for el, item in s.iteritems():
  132. assert s.at[el] == s.loc[el] == item
  133. for i in range(len(s)):
  134. assert s.iat[i] == s.iloc[i] == i + 1
  135. with pytest.raises(KeyError):
  136. s.at[4]
  137. with pytest.raises(KeyError):
  138. s.loc[4]
  139. def test_mixed_index_at_iat_loc_iloc_dataframe(self):
  140. # GH 19860
  141. df = DataFrame([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]],
  142. columns=['a', 'b', 'c', 1, 2])
  143. for rowIdx, row in df.iterrows():
  144. for el, item in row.iteritems():
  145. assert df.at[rowIdx, el] == df.loc[rowIdx, el] == item
  146. for row in range(2):
  147. for i in range(5):
  148. assert df.iat[row, i] == df.iloc[row, i] == row * 5 + i
  149. with pytest.raises(KeyError):
  150. df.at[0, 3]
  151. with pytest.raises(KeyError):
  152. df.loc[0, 3]
  153. def test_iat_setter_incompatible_assignment(self):
  154. # GH 23236
  155. result = DataFrame({'a': [0, 1], 'b': [4, 5]})
  156. result.iat[0, 0] = None
  157. expected = DataFrame({"a": [None, 1], "b": [4, 5]})
  158. tm.assert_frame_equal(result, expected)