test_values.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import numpy as np
  2. import pytest
  3. import pandas.util._test_decorators as td
  4. from pandas import (
  5. DataFrame,
  6. NaT,
  7. Series,
  8. Timestamp,
  9. date_range,
  10. period_range,
  11. )
  12. import pandas._testing as tm
  13. class TestDataFrameValues:
  14. @td.skip_array_manager_invalid_test
  15. def test_values(self, float_frame, using_copy_on_write):
  16. if using_copy_on_write:
  17. with pytest.raises(ValueError, match="read-only"):
  18. float_frame.values[:, 0] = 5.0
  19. assert (float_frame.values[:, 0] != 5).all()
  20. else:
  21. float_frame.values[:, 0] = 5.0
  22. assert (float_frame.values[:, 0] == 5).all()
  23. def test_more_values(self, float_string_frame):
  24. values = float_string_frame.values
  25. assert values.shape[1] == len(float_string_frame.columns)
  26. def test_values_mixed_dtypes(self, float_frame, float_string_frame):
  27. frame = float_frame
  28. arr = frame.values
  29. frame_cols = frame.columns
  30. for i, row in enumerate(arr):
  31. for j, value in enumerate(row):
  32. col = frame_cols[j]
  33. if np.isnan(value):
  34. assert np.isnan(frame[col][i])
  35. else:
  36. assert value == frame[col][i]
  37. # mixed type
  38. arr = float_string_frame[["foo", "A"]].values
  39. assert arr[0, 0] == "bar"
  40. df = DataFrame({"complex": [1j, 2j, 3j], "real": [1, 2, 3]})
  41. arr = df.values
  42. assert arr[0, 0] == 1j
  43. def test_values_duplicates(self):
  44. df = DataFrame(
  45. [[1, 2, "a", "b"], [1, 2, "a", "b"]], columns=["one", "one", "two", "two"]
  46. )
  47. result = df.values
  48. expected = np.array([[1, 2, "a", "b"], [1, 2, "a", "b"]], dtype=object)
  49. tm.assert_numpy_array_equal(result, expected)
  50. def test_values_with_duplicate_columns(self):
  51. df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"])
  52. result = df.values
  53. expected = np.array([[1, 2.5], [3, 4.5]])
  54. assert (result == expected).all().all()
  55. @pytest.mark.parametrize("constructor", [date_range, period_range])
  56. def test_values_casts_datetimelike_to_object(self, constructor):
  57. series = Series(constructor("2000-01-01", periods=10, freq="D"))
  58. expected = series.astype("object")
  59. df = DataFrame({"a": series, "b": np.random.randn(len(series))})
  60. result = df.values.squeeze()
  61. assert (result[:, 0] == expected.values).all()
  62. df = DataFrame({"a": series, "b": ["foo"] * len(series)})
  63. result = df.values.squeeze()
  64. assert (result[:, 0] == expected.values).all()
  65. def test_frame_values_with_tz(self):
  66. tz = "US/Central"
  67. df = DataFrame({"A": date_range("2000", periods=4, tz=tz)})
  68. result = df.values
  69. expected = np.array(
  70. [
  71. [Timestamp("2000-01-01", tz=tz)],
  72. [Timestamp("2000-01-02", tz=tz)],
  73. [Timestamp("2000-01-03", tz=tz)],
  74. [Timestamp("2000-01-04", tz=tz)],
  75. ]
  76. )
  77. tm.assert_numpy_array_equal(result, expected)
  78. # two columns, homogeneous
  79. df["B"] = df["A"]
  80. result = df.values
  81. expected = np.concatenate([expected, expected], axis=1)
  82. tm.assert_numpy_array_equal(result, expected)
  83. # three columns, heterogeneous
  84. est = "US/Eastern"
  85. df["C"] = df["A"].dt.tz_convert(est)
  86. new = np.array(
  87. [
  88. [Timestamp("2000-01-01T01:00:00", tz=est)],
  89. [Timestamp("2000-01-02T01:00:00", tz=est)],
  90. [Timestamp("2000-01-03T01:00:00", tz=est)],
  91. [Timestamp("2000-01-04T01:00:00", tz=est)],
  92. ]
  93. )
  94. expected = np.concatenate([expected, new], axis=1)
  95. result = df.values
  96. tm.assert_numpy_array_equal(result, expected)
  97. def test_interleave_with_tzaware(self, timezone_frame):
  98. # interleave with object
  99. result = timezone_frame.assign(D="foo").values
  100. expected = np.array(
  101. [
  102. [
  103. Timestamp("2013-01-01 00:00:00"),
  104. Timestamp("2013-01-02 00:00:00"),
  105. Timestamp("2013-01-03 00:00:00"),
  106. ],
  107. [
  108. Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
  109. NaT,
  110. Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
  111. ],
  112. [
  113. Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
  114. NaT,
  115. Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
  116. ],
  117. ["foo", "foo", "foo"],
  118. ],
  119. dtype=object,
  120. ).T
  121. tm.assert_numpy_array_equal(result, expected)
  122. # interleave with only datetime64[ns]
  123. result = timezone_frame.values
  124. expected = np.array(
  125. [
  126. [
  127. Timestamp("2013-01-01 00:00:00"),
  128. Timestamp("2013-01-02 00:00:00"),
  129. Timestamp("2013-01-03 00:00:00"),
  130. ],
  131. [
  132. Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
  133. NaT,
  134. Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
  135. ],
  136. [
  137. Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
  138. NaT,
  139. Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
  140. ],
  141. ],
  142. dtype=object,
  143. ).T
  144. tm.assert_numpy_array_equal(result, expected)
  145. def test_values_interleave_non_unique_cols(self):
  146. df = DataFrame(
  147. [[Timestamp("20130101"), 3.5], [Timestamp("20130102"), 4.5]],
  148. columns=["x", "x"],
  149. index=[1, 2],
  150. )
  151. df_unique = df.copy()
  152. df_unique.columns = ["x", "y"]
  153. assert df_unique.values.shape == df.values.shape
  154. tm.assert_numpy_array_equal(df_unique.values[0], df.values[0])
  155. tm.assert_numpy_array_equal(df_unique.values[1], df.values[1])
  156. def test_values_numeric_cols(self, float_frame):
  157. float_frame["foo"] = "bar"
  158. values = float_frame[["A", "B", "C", "D"]].values
  159. assert values.dtype == np.float64
  160. def test_values_lcd(self, mixed_float_frame, mixed_int_frame):
  161. # mixed lcd
  162. values = mixed_float_frame[["A", "B", "C", "D"]].values
  163. assert values.dtype == np.float64
  164. values = mixed_float_frame[["A", "B", "C"]].values
  165. assert values.dtype == np.float32
  166. values = mixed_float_frame[["C"]].values
  167. assert values.dtype == np.float16
  168. # GH#10364
  169. # B uint64 forces float because there are other signed int types
  170. values = mixed_int_frame[["A", "B", "C", "D"]].values
  171. assert values.dtype == np.float64
  172. values = mixed_int_frame[["A", "D"]].values
  173. assert values.dtype == np.int64
  174. # B uint64 forces float because there are other signed int types
  175. values = mixed_int_frame[["A", "B", "C"]].values
  176. assert values.dtype == np.float64
  177. # as B and C are both unsigned, no forcing to float is needed
  178. values = mixed_int_frame[["B", "C"]].values
  179. assert values.dtype == np.uint64
  180. values = mixed_int_frame[["A", "C"]].values
  181. assert values.dtype == np.int32
  182. values = mixed_int_frame[["C", "D"]].values
  183. assert values.dtype == np.int64
  184. values = mixed_int_frame[["A"]].values
  185. assert values.dtype == np.int32
  186. values = mixed_int_frame[["C"]].values
  187. assert values.dtype == np.uint8
  188. class TestPrivateValues:
  189. @td.skip_array_manager_invalid_test
  190. def test_private_values_dt64tz(self, using_copy_on_write):
  191. dta = date_range("2000", periods=4, tz="US/Central")._data.reshape(-1, 1)
  192. df = DataFrame(dta, columns=["A"])
  193. tm.assert_equal(df._values, dta)
  194. if using_copy_on_write:
  195. assert not np.shares_memory(df._values._ndarray, dta._ndarray)
  196. else:
  197. # we have a view
  198. assert np.shares_memory(df._values._ndarray, dta._ndarray)
  199. # TimedeltaArray
  200. tda = dta - dta
  201. df2 = df - df
  202. tm.assert_equal(df2._values, tda)
  203. @td.skip_array_manager_invalid_test
  204. def test_private_values_dt64tz_multicol(self, using_copy_on_write):
  205. dta = date_range("2000", periods=8, tz="US/Central")._data.reshape(-1, 2)
  206. df = DataFrame(dta, columns=["A", "B"])
  207. tm.assert_equal(df._values, dta)
  208. if using_copy_on_write:
  209. assert not np.shares_memory(df._values._ndarray, dta._ndarray)
  210. else:
  211. # we have a view
  212. assert np.shares_memory(df._values._ndarray, dta._ndarray)
  213. # TimedeltaArray
  214. tda = dta - dta
  215. df2 = df - df
  216. tm.assert_equal(df2._values, tda)
  217. def test_private_values_dt64_multiblock(self):
  218. dta = date_range("2000", periods=8)._data
  219. df = DataFrame({"A": dta[:4]}, copy=False)
  220. df["B"] = dta[4:]
  221. assert len(df._mgr.arrays) == 2
  222. result = df._values
  223. expected = dta.reshape(2, 4).T
  224. tm.assert_equal(result, expected)