code: """
  Tests for 2D compatibility.
  """
  import numpy as np
  import pytest
  
  from pandas._libs.missing import is_matching_na
  
  import pandas as pd
  from pandas.core.arrays.integer import INT_STR_TO_DTYPE
  from pandas.tests.extension.base.base import BaseExtensionTests
  
  
  class Dim2CompatTests(BaseExtensionTests):
      def test_transpose(self, data):
          arr2d = data.repeat(2).reshape(-1, 2)
          shape = arr2d.shape
          assert shape[0] != shape[-1]  # otherwise the rest of the test is useless
  
          assert arr2d.T.shape == shape[::-1]
  
      def test_frame_from_2d_array(self, data):
          arr2d = data.repeat(2).reshape(-1, 2)
  
          df = pd.DataFrame(arr2d)
          expected = pd.DataFrame({0: arr2d[:, 0], 1: arr2d[:, 1]})
          self.assert_frame_equal(df, expected)
  
      def test_swapaxes(self, data):
          arr2d = data.repeat(2).reshape(-1, 2)
  
          result = arr2d.swapaxes(0, 1)
          expected = arr2d.T
          self.assert_extension_array_equal(result, expected)
  
      def test_delete_2d(self, data):
          arr2d = data.repeat(3).reshape(-1, 3)
  
          # axis = 0
          result = arr2d.delete(1, axis=0)
          expected = data.delete(1).repeat(3).reshape(-1, 3)
          self.assert_extension_array_equal(result, expected)
  
          # axis = 1
          result = arr2d.delete(1, axis=1)
          expected = data.repeat(2).reshape(-1, 2)
          self.assert_extension_array_equal(result, expected)
  
      def test_take_2d(self, data):
          arr2d = data.reshape(-1, 1)
  
          result = arr2d.take([0, 0, -1], axis=0)
  
          expected = data.take([0, 0, -1]).reshape(-1, 1)
          self.assert_extension_array_equal(result, expected)
  
      def test_repr_2d(self, data):
          # this could fail in a corner case where an element contained the name
          res = repr(data.reshape(1, -1))
          assert res.count(f"<{type(data).__name__}") == 1
  
          res = repr(data.reshape(-1, 1))
          assert res.count(f"<{type(data).__name__}") == 1
  
      def test_reshape(self, data):
          arr2d = data.reshape(-1, 1)
          assert arr2d.shape == (data.size, 1)
          assert len(arr2d) == len(data)
  
          arr2d = data.reshape((-1, 1))
          assert arr2d.shape == (data.size, 1)
          assert len(arr2d) == len(data)
  
          with pytest.raises(ValueError):
              data.reshape((data.size, 2))
          with pytest.raises(ValueError):
              data.reshape(data.size, 2)
  
      def test_getitem_2d(self, data):
          arr2d = data.reshape(1, -1)
  
          result = arr2d[0]
          self.assert_extension_array_equal(result, data)
  
          with pytest.raises(IndexError):
              arr2d[1]
  
          with pytest.raises(IndexError):
              arr2d[-2]
  
          result = arr2d[:]
          self.assert_extension_array_equal(result, arr2d)
  
          result = arr2d[:, :]
          self.assert_extension_array_equal(result, arr2d)
  
          result = arr2d[:, 0]
          expected = data[[0]]
          self.assert_extension_array_equal(result, expected)
  
          # dimension-expanding getitem on 1D
          result = data[:, np.newaxis]
          self.assert_extension_array_equal(result, arr2d.T)
  
      def test_iter_2d(self, data):
          arr2d = data.reshape(1, -1)
  
          objs = list(iter(arr2d))
          assert len(objs) == arr2d.shape[0]
  
          for obj in objs:
              assert isinstance(obj, type(data))
              assert obj.dtype == data.dtype
              assert obj.ndim == 1
              assert len(obj) == arr2d.shape[1]
  
      def test_tolist_2d(self, data):
          arr2d = data.reshape(1, -1)
  
          result = arr2d.tolist()
          expected = [data.tolist()]
  
          assert isinstance(result, list)
          assert all(isinstance(x, list) for x in result)
  
          assert result == expected
  
      def test_concat_2d(self, data):
          left = type(data)._concat_same_type([data, data]).reshape(-1, 2)
          right = left.copy()
  
          # axis=0
          result = left._concat_same_type([left, right], axis=0)
          expected = data._concat_same_type([data] * 4).reshape(-1, 2)
          self.assert_extension_array_equal(result, expected)
  
          # axis=1
          result = left._concat_same_type([left, right], axis=1)
          assert result.shape == (len(data), 4)
          self.assert_extension_array_equal(result[:, :2], left)
          self.assert_extension_array_equal(result[:, 2:], right)
  
          # axis > 1 -> invalid
          msg = "axis 2 is out of bounds for array of dimension 2"
          with pytest.raises(ValueError, match=msg):
              left._concat_same_type([left, right], axis=2)
  
      @pytest.mark.parametrize("method", ["backfill", "pad"])
      def test_fillna_2d_method(self, data_missing, method):
          arr = data_missing.repeat(2).reshape(2, 2)
          assert arr[0].isna().all()
          assert not arr[1].isna().any()
  
          result = arr.fillna(method=method)
  
          expected = data_missing.fillna(method=method).repeat(2).reshape(2, 2)
          self.assert_extension_array_equal(result, expected)
  
      @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"])
      def test_reductions_2d_axis_none(self, data, method):
          arr2d = data.reshape(1, -1)
  
          err_expected = None
          err_result = None
          try:
              expected = getattr(data, method)()
          except Exception as err:
              # if the 1D reduction is invalid, the 2D reduction should be as well
              err_expected = err
              try:
                  result = getattr(arr2d, method)(axis=None)
              except Exception as err2:
                  err_result = err2
  
          else:
              result = getattr(arr2d, method)(axis=None)
  
          if err_result is not None or err_expected is not None:
              assert type(err_result) == type(err_expected)
              return
  
          assert is_matching_na(result, expected) or result == expected
  
      @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"])
      def test_reductions_2d_axis0(self, data, method):
          arr2d = data.reshape(1, -1)
  
          kwargs = {}
          if method == "std":
              # pass ddof=0 so we get all-zero std instead of all-NA std
              kwargs["ddof"] = 0
  
          try:
              result = getattr(arr2d, method)(axis=0, **kwargs)
          except Exception as err:
              try:
                  getattr(data, method)()
              except Exception as err2:
                  assert type(err) == type(err2)
                  return
              else:
                  raise AssertionError("Both reductions should raise or neither")
  
          def get_reduction_result_dtype(dtype):
              # windows and 32bit builds will in some cases have int32/uint32
              #  where other builds will have int64/uint64.
              if dtype.itemsize == 8:
                  return dtype
              elif dtype.kind in "ib":
                  return INT_STR_TO_DTYPE[np.dtype(int).name]
              else:
                  # i.e. dtype.kind == "u"
                  return INT_STR_TO_DTYPE[np.dtype(np.uint).name]
  
          if method in ["mean", "median", "sum", "prod"]:
              # std and var are not dtype-preserving
              expected = data
              if method in ["sum", "prod"] and data.dtype.kind in "iub":
                  dtype = get_reduction_result_dtype(data.dtype)
  
                  expected = data.astype(dtype)
                  if data.dtype.kind == "b" and method in ["sum", "prod"]:
                      # We get IntegerArray instead of BooleanArray
                      pass
                  else:
                      assert type(expected) == type(data), type(expected)
                  assert dtype == expected.dtype
  
              self.assert_extension_array_equal(result, expected)
          elif method == "std":
              self.assert_extension_array_equal(result, data - data)
          # punt on method == "var"
  
      @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"])
      def test_reductions_2d_axis1(self, data, method):
          arr2d = data.reshape(1, -1)
  
          try:
              result = getattr(arr2d, method)(axis=1)
          except Exception as err:
              try:
                  getattr(data, method)()
              except Exception as err2:
                  assert type(err) == type(err2)
                  return
              else:
                  raise AssertionError("Both reductions should raise or neither")
  
          # not necessarily type/dtype-preserving, so weaker assertions
          assert result.shape == (1,)
          expected_scalar = getattr(data, method)()
          res = result[0]
          assert is_matching_na(res, expected_scalar) or res == expected_scalar
  
  
  class NDArrayBacked2DTests(Dim2CompatTests):
      # More specific tests for NDArrayBackedExtensionArray subclasses
  
      def test_copy_order(self, data):
          # We should be matching numpy semantics for the "order" keyword in 'copy'
          arr2d = data.repeat(2).reshape(-1, 2)
          assert arr2d._ndarray.flags["C_CONTIGUOUS"]
  
          res = arr2d.copy()
          assert res._ndarray.flags["C_CONTIGUOUS"]
  
          res = arr2d[::2, ::2].copy()
          assert res._ndarray.flags["C_CONTIGUOUS"]
  
          res = arr2d.copy("F")
          assert not res._ndarray.flags["C_CONTIGUOUS"]
          assert res._ndarray.flags["F_CONTIGUOUS"]
  
          res = arr2d.copy("K")
          assert res._ndarray.flags["C_CONTIGUOUS"]
  
          res = arr2d.T.copy("K")
          assert not res._ndarray.flags["C_CONTIGUOUS"]
          assert res._ndarray.flags["F_CONTIGUOUS"]
  
          # order not accepted by numpy
          msg = r"order must be one of 'C', 'F', 'A', or 'K' \(got 'Q'\)"
          with pytest.raises(ValueError, match=msg):
              arr2d.copy("Q")
  
          # neither contiguity
          arr_nc = arr2d[::2]
          assert not arr_nc._ndarray.flags["C_CONTIGUOUS"]
          assert not arr_nc._ndarray.flags["F_CONTIGUOUS"]
  
          assert arr_nc.copy()._ndarray.flags["C_CONTIGUOUS"]
          assert not arr_nc.copy()._ndarray.flags["F_CONTIGUOUS"]
  
          assert arr_nc.copy("C")._ndarray.flags["C_CONTIGUOUS"]
          assert not arr_nc.copy("C")._ndarray.flags["F_CONTIGUOUS"]
  
          assert not arr_nc.copy("F")._ndarray.flags["C_CONTIGUOUS"]
          assert arr_nc.copy("F")._ndarray.flags["F_CONTIGUOUS"]
  
          assert arr_nc.copy("K")._ndarray.flags["C_CONTIGUOUS"]
          assert not arr_nc.copy("K")._ndarray.flags["F_CONTIGUOUS"]
   import numpy as np
  import pytest
  
  import pandas.util._test_decorators as td
  
  from pandas import (
      DataFrame,
      NaT,
      Series,
      Timestamp,
      date_range,
      period_range,
  )
  import pandas._testing as tm
  
  
  class TestDataFrameValues:
      @td.skip_array_manager_invalid_test
      def test_values(self, float_frame):
          float_frame.values[:, 0] = 5.0
          assert (float_frame.values[:, 0] == 5).all()
  
      def test_more_values(self, float_string_frame):
          values = float_string_frame.values
          assert values.shape[1] == len(float_string_frame.columns)
  
      def test_values_mixed_dtypes(self, float_frame, float_string_frame):
          frame = float_frame
          arr = frame.values
  
          frame_cols = frame.columns
          for i, row in enumerate(arr):
              for j, value in enumerate(row):
                  col = frame_cols[j]
                  if np.isnan(value):
                      assert np.isnan(frame[col][i])
                  else:
                      assert value == frame[col][i]
  
          # mixed type
          arr = float_string_frame[["foo", "A"]].values
          assert arr[0, 0] == "bar"
  
          df = DataFrame({"complex": [1j, 2j, 3j], "real": [1, 2, 3]})
          arr = df.values
          assert arr[0, 0] == 1j
  
      def test_values_duplicates(self):
          df = DataFrame(
              [[1, 2, "a", "b"], [1, 2, "a", "b"]], columns=["one", "one", "two", "two"]
          )
  
          result = df.values
          expected = np.array([[1, 2, "a", "b"], [1, 2, "a", "b"]], dtype=object)
  
          tm.assert_numpy_array_equal(result, expected)
  
      def test_values_with_duplicate_columns(self):
          df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"])
          result = df.values
          expected = np.array([[1, 2.5], [3, 4.5]])
          assert (result == expected).all().all()
  
      @pytest.mark.parametrize("constructor", [date_range, period_range])
      def test_values_casts_datetimelike_to_object(self, constructor):
          series = Series(constructor("2000-01-01", periods=10, freq="D"))
  
          expected = series.astype("object")
  
          df = DataFrame({"a": series, "b": np.random.randn(len(series))})
  
          result = df.values.squeeze()
          assert (result[:, 0] == expected.values).all()
  
          df = DataFrame({"a": series, "b": ["foo"] * len(series)})
  
          result = df.values.squeeze()
          assert (result[:, 0] == expected.values).all()
  
      def test_frame_values_with_tz(self):
          tz = "US/Central"
          df = DataFrame({"A": date_range("2000", periods=4, tz=tz)})
          result = df.values
          expected = np.array(
              [
                  [Timestamp("2000-01-01", tz=tz)],
                  [Timestamp("2000-01-02", tz=tz)],
                  [Timestamp("2000-01-03", tz=tz)],
                  [Timestamp("2000-01-04", tz=tz)],
              ]
          )
          tm.assert_numpy_array_equal(result, expected)
  
          # two columns, homogeneous
  
          df["B"] = df["A"]
          result = df.values
          expected = np.concatenate([expected, expected], axis=1)
          tm.assert_numpy_array_equal(result, expected)
  
          # three columns, heterogeneous
          est = "US/Eastern"
          df["C"] = df["A"].dt.tz_convert(est)
  
          new = np.array(
              [
                  [Timestamp("2000-01-01T01:00:00", tz=est)],
                  [Timestamp("2000-01-02T01:00:00", tz=est)],
                  [Timestamp("2000-01-03T01:00:00", tz=est)],
                  [Timestamp("2000-01-04T01:00:00", tz=est)],
              ]
          )
          expected = np.concatenate([expected, new], axis=1)
          result = df.values
          tm.assert_numpy_array_equal(result, expected)
  
      def test_interleave_with_tzaware(self, timezone_frame):
  
          # interleave with object
          result = timezone_frame.assign(D="foo").values
          expected = np.array(
              [
                  [
                      Timestamp("2013-01-01 00:00:00"),
                      Timestamp("2013-01-02 00:00:00"),
                      Timestamp("2013-01-03 00:00:00"),
                  ],
                  [
                      Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
                      NaT,
                      Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
                  ],
                  [
                      Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
                      NaT,
                      Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
                  ],
                  ["foo", "foo", "foo"],
              ],
              dtype=object,
          ).T
          tm.assert_numpy_array_equal(result, expected)
  
          # interleave with only datetime64[ns]
          result = timezone_frame.values
          expected = np.array(
              [
                  [
                      Timestamp("2013-01-01 00:00:00"),
                      Timestamp("2013-01-02 00:00:00"),
                      Timestamp("2013-01-03 00:00:00"),
                  ],
                  [
                      Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
                      NaT,
                      Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
                  ],
                  [
                      Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
                      NaT,
                      Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
                  ],
              ],
              dtype=object,
          ).T
          tm.assert_numpy_array_equal(result, expected)
  
      def test_values_interleave_non_unique_cols(self):
          df = DataFrame(
              [[Timestamp("20130101"), 3.5], [Timestamp("20130102"), 4.5]],
              columns=["x", "x"],
              index=[1, 2],
          )
  
          df_unique = df.copy()
          df_unique.columns = ["x", "y"]
          assert df_unique.values.shape == df.values.shape
          tm.assert_numpy_array_equal(df_unique.values[0], df.values[0])
          tm.assert_numpy_array_equal(df_unique.values[1], df.values[1])
  
      def test_values_numeric_cols(self, float_frame):
          float_frame["foo"] = "bar"
  
          values = float_frame[["A", "B", "C", "D"]].values
          assert values.dtype == np.float64
  
      def test_values_lcd(self, mixed_float_frame, mixed_int_frame):
  
          # mixed lcd
          values = mixed_float_frame[["A", "B", "C", "D"]].values
          assert values.dtype == np.float64
  
          values = mixed_float_frame[["A", "B", "C"]].values
          assert values.dtype == np.float32
  
          values = mixed_float_frame[["C"]].values
          assert values.dtype == np.float16
  
          # GH#10364
          # B uint64 forces float because there are other signed int types
          values = mixed_int_frame[["A", "B", "C", "D"]].values
          assert values.dtype == np.float64
  
          values = mixed_int_frame[["A", "D"]].values
          assert values.dtype == np.int64
  
          # B uint64 forces float because there are other signed int types
          values = mixed_int_frame[["A", "B", "C"]].values
          assert values.dtype == np.float64
  
          # as B and C are both unsigned, no forcing to float is needed
          values = mixed_int_frame[["B", "C"]].values
          assert values.dtype == np.uint64
  
          values = mixed_int_frame[["A", "C"]].values
          assert values.dtype == np.int32
  
          values = mixed_int_frame[["C", "D"]].values
          assert values.dtype == np.int64
  
          values = mixed_int_frame[["A"]].values
          assert values.dtype == np.int32
  
          values = mixed_int_frame[["C"]].values
          assert values.dtype == np.uint8
  
  
  class TestPrivateValues:
      @td.skip_array_manager_invalid_test
      def test_private_values_dt64tz(self):
          dta = date_range("2000", periods=4, tz="US/Central")._data.reshape(-1, 1)
  
          df = DataFrame(dta, columns=["A"])
          tm.assert_equal(df._values, dta)
  
          # we have a view
          assert np.shares_memory(df._values._ndarray, dta._ndarray)
  
          # TimedeltaArray
          tda = dta - dta
          df2 = df - df
          tm.assert_equal(df2._values, tda)
  
      @td.skip_array_manager_invalid_test
      def test_private_values_dt64tz_multicol(self):
          dta = date_range("2000", periods=8, tz="US/Central")._data.reshape(-1, 2)
  
          df = DataFrame(dta, columns=["A", "B"])
          tm.assert_equal(df._values, dta)
  
          # we have a view
          assert np.shares_memory(df._values._ndarray, dta._ndarray)
  
          # TimedeltaArray
          tda = dta - dta
          df2 = df - df
          tm.assert_equal(df2._values, tda)
  
      def test_private_values_dt64_multiblock(self, using_array_manager, request):
          if using_array_manager:
              mark = pytest.mark.xfail(reason="returns ndarray")
              request.node.add_marker(mark)
  
          dta = date_range("2000", periods=8)._data
  
          df = DataFrame({"A": dta[:4]}, copy=False)
          df["B"] = dta[4:]
  
          assert len(df._mgr.arrays) == 2
  
          result = df._values
          expected = dta.reshape(2, 4).T
          tm.assert_equal(result, expected)
   """See https://github.com/numpy/numpy/pull/11937.
  
  """
  import sys
  import os
  import uuid
  from importlib import import_module
  import pytest
  
  import numpy.f2py
  
  from numpy.testing import assert_equal
  from . import util
  
  
  def setup_module():
      if not util.has_c_compiler():
          pytest.skip("Needs C compiler")
      if not util.has_f77_compiler():
          pytest.skip('Needs FORTRAN 77 compiler')
  
  
  # extra_args can be a list (since gh-11937) or string.
  # also test absence of extra_args
  @pytest.mark.parametrize(
      "extra_args", [['--noopt', '--debug'], '--noopt --debug', '']
      )
  @pytest.mark.leaks_references(reason="Imported module seems never deleted.")
  def test_f2py_init_compile(extra_args):
      # flush through the f2py __init__ compile() function code path as a
      # crude test for input handling following migration from
      # exec_command() to subprocess.check_output() in gh-11937
  
      # the Fortran 77 syntax requires 6 spaces before any commands, but
      # more space may be added/
      fsource =  """
          integer function foo()
          foo = 10 + 5
          return
          end
      """
      # use various helper functions in util.py to enable robust build /
      # compile and reimport cycle in test suite
      moddir = util.get_module_dir()
      modname = util.get_temp_module_name()
  
      cwd = os.getcwd()
      target = os.path.join(moddir, str(uuid.uuid4()) + '.f')
      # try running compile() with and without a source_fn provided so
      # that the code path where a temporary file for writing Fortran
      # source is created is also explored
      for source_fn in [target, None]:
          # mimic the path changing behavior used by build_module() in
          # util.py, but don't actually use build_module() because it has
          # its own invocation of subprocess that circumvents the
          # f2py.compile code block under test
          try:
              os.chdir(moddir)
              ret_val = numpy.f2py.compile(
                  fsource,
                  modulename=modname,
                  extra_args=extra_args,
                  source_fn=source_fn
                  )
          finally:
              os.chdir(cwd)
  
          # check for compile success return value
          assert_equal(ret_val, 0)
  
          # we are not currently able to import the Python-Fortran
          # interface module on Windows / Appveyor, even though we do get
          # successful compilation on that platform with Python 3.x
          if sys.platform != 'win32':
              # check for sensible result of Fortran function; that means
              # we can import the module name in Python and retrieve the
              # result of the sum operation
              return_check = import_module(modname)
              calc_result = return_check.foo()
              assert_equal(calc_result, 15)
              # Removal from sys.modules, is not as such necessary. Even with
              # removal, the module (dict) stays alive.
              del sys.modules[modname]
  
  
  def test_f2py_init_compile_failure():
      # verify an appropriate integer status value returned by
      # f2py.compile() when invalid Fortran is provided
      ret_val = numpy.f2py.compile(b"invalid")
      assert_equal(ret_val, 1)
  
  
  def test_f2py_init_compile_bad_cmd():
      # verify that usage of invalid command in f2py.compile() returns
      # status value of 127 for historic consistency with exec_command()
      # error handling
  
      # patch the sys Python exe path temporarily to induce an OSError
      # downstream NOTE: how bad of an idea is this patching?
      try:
          temp = sys.executable
          sys.executable = 'does not exist'
  
          # the OSError should take precedence over invalid Fortran
          ret_val = numpy.f2py.compile(b"invalid")
          assert_equal(ret_val, 127)
      finally:
          sys.executable = temp
  
  
  @pytest.mark.parametrize('fsource',
          ['program test_f2py\nend program test_f2py',
           b'program test_f2py\nend program test_f2py',])
  def test_compile_from_strings(tmpdir, fsource):
      # Make sure we can compile str and bytes gh-12796
      cwd = os.getcwd()
      try:
          os.chdir(str(tmpdir))
          ret_val = numpy.f2py.compile(
                  fsource,
                  modulename='test_compile_from_strings',
                  extension='.f90')
          assert_equal(ret_val, 0)
      finally:
          os.chdir(cwd)
  
apis: numpy.dtype pandas.DataFrame pandas._libs.missing.is_matching_na
apis: pandas._testing.assert_numpy_array_equal pandas.date_range numpy.shares_memory pandas.DataFrame pandas._testing.assert_equal numpy.isnan numpy.array numpy.concatenate pandas.Timestamp
apis: numpy.testing.assert_equal