Python pandas.core.dtypes.cast.construct_1d_object_array_from_listlike() Examples

The following are 19 code examples of pandas.core.dtypes.cast.construct_1d_object_array_from_listlike(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pandas.core.dtypes.cast , or try the search function .
Example #1
Source File: common.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _asarray_tuplesafe(values, dtype=None):
    from pandas.core.index import Index

    if not (isinstance(values, (list, tuple)) or hasattr(values, '__array__')):
        values = list(values)
    elif isinstance(values, Index):
        return values.values

    if isinstance(values, list) and dtype in [np.object_, object]:
        return construct_1d_object_array_from_listlike(values)

    result = np.asarray(values, dtype=dtype)

    if issubclass(result.dtype.type, compat.string_types):
        result = np.asarray(values, dtype=object)

    if result.ndim == 2:
        # Avoid building an array of arrays:
        # TODO: verify whether any path hits this except #18819 (invalid)
        values = [tuple(x) for x in values]
        result = construct_1d_object_array_from_listlike(values)

    return result 
Example #2
Source File: test_constructor.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_from_product_datetimeindex():
    dt_index = date_range('2000-01-01', periods=2)
    mi = pd.MultiIndex.from_product([[1, 2], dt_index])
    etalon = construct_1d_object_array_from_listlike([
        (1, pd.Timestamp('2000-01-01')),
        (1, pd.Timestamp('2000-01-02')),
        (2, pd.Timestamp('2000-01-01')),
        (2, pd.Timestamp('2000-01-02')),
    ])
    tm.assert_numpy_array_equal(mi.values, etalon) 
Example #3
Source File: test_multi.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_values_boxed(self):
        tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT),
                  (3, pd.Timestamp('2000-01-03')),
                  (1, pd.Timestamp('2000-01-04')),
                  (2, pd.Timestamp('2000-01-02')),
                  (3, pd.Timestamp('2000-01-03'))]
        result = pd.MultiIndex.from_tuples(tuples)
        expected = construct_1d_object_array_from_listlike(tuples)
        tm.assert_numpy_array_equal(result.values, expected)
        # Check that code branches for boxed values produce identical results
        tm.assert_numpy_array_equal(result.values[:4], result[:4].values) 
Example #4
Source File: test_multi.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_from_product_datetimeindex(self):
        dt_index = date_range('2000-01-01', periods=2)
        mi = pd.MultiIndex.from_product([[1, 2], dt_index])
        etalon = construct_1d_object_array_from_listlike([(1, pd.Timestamp(
            '2000-01-01')), (1, pd.Timestamp('2000-01-02')), (2, pd.Timestamp(
                '2000-01-01')), (2, pd.Timestamp('2000-01-02'))])
        tm.assert_numpy_array_equal(mi.values, etalon) 
Example #5
Source File: test_constructor.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_from_product_datetimeindex():
    dt_index = date_range('2000-01-01', periods=2)
    mi = pd.MultiIndex.from_product([[1, 2], dt_index])
    etalon = construct_1d_object_array_from_listlike([
        (1, pd.Timestamp('2000-01-01')),
        (1, pd.Timestamp('2000-01-02')),
        (2, pd.Timestamp('2000-01-01')),
        (2, pd.Timestamp('2000-01-02')),
    ])
    tm.assert_numpy_array_equal(mi.values, etalon) 
Example #6
Source File: test_integrity.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_values_boxed():
    tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT),
              (3, pd.Timestamp('2000-01-03')),
              (1, pd.Timestamp('2000-01-04')),
              (2, pd.Timestamp('2000-01-02')),
              (3, pd.Timestamp('2000-01-03'))]
    result = pd.MultiIndex.from_tuples(tuples)
    expected = construct_1d_object_array_from_listlike(tuples)
    tm.assert_numpy_array_equal(result.values, expected)
    # Check that code branches for boxed values produce identical results
    tm.assert_numpy_array_equal(result.values[:4], result[:4].values) 
Example #7
Source File: test_construct_object_arr.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_cast_1d_array_invalid_scalar(val):
    with pytest.raises(TypeError, match="has no len()"):
        construct_1d_object_array_from_listlike(val) 
Example #8
Source File: test_construct_object_arr.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_cast_1d_array(datum1, datum2):
    data = [datum1, datum2]
    result = construct_1d_object_array_from_listlike(data)

    # Direct comparison fails: https://github.com/numpy/numpy/issues/10218
    assert result.dtype == "object"
    assert list(result) == data 
Example #9
Source File: test_constructor.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_from_product_datetimeindex():
    dt_index = date_range('2000-01-01', periods=2)
    mi = pd.MultiIndex.from_product([[1, 2], dt_index])
    etalon = construct_1d_object_array_from_listlike([
        (1, pd.Timestamp('2000-01-01')),
        (1, pd.Timestamp('2000-01-02')),
        (2, pd.Timestamp('2000-01-01')),
        (2, pd.Timestamp('2000-01-02')),
    ])
    tm.assert_numpy_array_equal(mi.values, etalon) 
Example #10
Source File: test_integrity.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_values_boxed():
    tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT),
              (3, pd.Timestamp('2000-01-03')),
              (1, pd.Timestamp('2000-01-04')),
              (2, pd.Timestamp('2000-01-02')),
              (3, pd.Timestamp('2000-01-03'))]
    result = pd.MultiIndex.from_tuples(tuples)
    expected = construct_1d_object_array_from_listlike(tuples)
    tm.assert_numpy_array_equal(result.values, expected)
    # Check that code branches for boxed values produce identical results
    tm.assert_numpy_array_equal(result.values[:4], result[:4].values) 
Example #11
Source File: test_multi.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_values_boxed(self):
        tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT),
                  (3, pd.Timestamp('2000-01-03')),
                  (1, pd.Timestamp('2000-01-04')),
                  (2, pd.Timestamp('2000-01-02')),
                  (3, pd.Timestamp('2000-01-03'))]
        result = pd.MultiIndex.from_tuples(tuples)
        expected = construct_1d_object_array_from_listlike(tuples)
        tm.assert_numpy_array_equal(result.values, expected)
        # Check that code branches for boxed values produce identical results
        tm.assert_numpy_array_equal(result.values[:4], result[:4].values) 
Example #12
Source File: test_multi.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_from_product_datetimeindex(self):
        dt_index = date_range('2000-01-01', periods=2)
        mi = pd.MultiIndex.from_product([[1, 2], dt_index])
        etalon = construct_1d_object_array_from_listlike([(1, pd.Timestamp(
            '2000-01-01')), (1, pd.Timestamp('2000-01-02')), (2, pd.Timestamp(
                '2000-01-01')), (2, pd.Timestamp('2000-01-02'))])
        tm.assert_numpy_array_equal(mi.values, etalon) 
Example #13
Source File: test_construct_object_arr.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_cast_1d_array_invalid_scalar(val):
    with pytest.raises(TypeError, match="has no len()"):
        construct_1d_object_array_from_listlike(val) 
Example #14
Source File: test_construct_object_arr.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_cast_1d_array(datum1, datum2):
    data = [datum1, datum2]
    result = construct_1d_object_array_from_listlike(data)

    # Direct comparison fails: https://github.com/numpy/numpy/issues/10218
    assert result.dtype == "object"
    assert list(result) == data 
Example #15
Source File: test_integrity.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_values_boxed():
    tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT),
              (3, pd.Timestamp('2000-01-03')),
              (1, pd.Timestamp('2000-01-04')),
              (2, pd.Timestamp('2000-01-02')),
              (3, pd.Timestamp('2000-01-03'))]
    result = pd.MultiIndex.from_tuples(tuples)
    expected = construct_1d_object_array_from_listlike(tuples)
    tm.assert_numpy_array_equal(result.values, expected)
    # Check that code branches for boxed values produce identical results
    tm.assert_numpy_array_equal(result.values[:4], result[:4].values) 
Example #16
Source File: test_constructors.py    From vnpy_crypto with MIT License 4 votes vote down vote up
def test_constructor_from_items(self):
        items = [(c, self.frame[c]) for c in self.frame.columns]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items)
        tm.assert_frame_equal(recons, self.frame)

        # pass some columns
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items, columns=['C', 'B', 'A'])
        tm.assert_frame_equal(recons, self.frame.loc[:, ['C', 'B', 'A']])

        # orient='index'

        row_items = [(idx, self.mixed_frame.xs(idx))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert recons['A'].dtype == np.float64

        with tm.assert_raises_regex(TypeError,
                                    "Must pass columns with "
                                    "orient='index'"):
            with tm.assert_produces_warning(FutureWarning,
                                            check_stacklevel=False):
                DataFrame.from_items(row_items, orient='index')

        # orient='index', but thar be tuples
        arr = construct_1d_object_array_from_listlike(
            [('bar', 'baz')] * len(self.mixed_frame))
        self.mixed_frame['foo'] = arr
        row_items = [(idx, list(self.mixed_frame.xs(idx)))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert isinstance(recons['foo'][0], tuple)

        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            rs = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
                                      orient='index',
                                      columns=['one', 'two', 'three'])
        xp = DataFrame([[1, 2, 3], [4, 5, 6]], index=['A', 'B'],
                       columns=['one', 'two', 'three'])
        tm.assert_frame_equal(rs, xp) 
Example #17
Source File: test_constructors.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 4 votes vote down vote up
def test_constructor_from_items(self):
        items = [(c, self.frame[c]) for c in self.frame.columns]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items)
        tm.assert_frame_equal(recons, self.frame)

        # pass some columns
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items, columns=['C', 'B', 'A'])
        tm.assert_frame_equal(recons, self.frame.loc[:, ['C', 'B', 'A']])

        # orient='index'

        row_items = [(idx, self.mixed_frame.xs(idx))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert recons['A'].dtype == np.float64

        msg = "Must pass columns with orient='index'"
        with pytest.raises(TypeError, match=msg):
            with tm.assert_produces_warning(FutureWarning,
                                            check_stacklevel=False):
                DataFrame.from_items(row_items, orient='index')

        # orient='index', but thar be tuples
        arr = construct_1d_object_array_from_listlike(
            [('bar', 'baz')] * len(self.mixed_frame))
        self.mixed_frame['foo'] = arr
        row_items = [(idx, list(self.mixed_frame.xs(idx)))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert isinstance(recons['foo'][0], tuple)

        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            rs = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
                                      orient='index',
                                      columns=['one', 'two', 'three'])
        xp = DataFrame([[1, 2, 3], [4, 5, 6]], index=['A', 'B'],
                       columns=['one', 'two', 'three'])
        tm.assert_frame_equal(rs, xp) 
Example #18
Source File: test_constructors.py    From recruit with Apache License 2.0 4 votes vote down vote up
def test_constructor_from_items(self):
        items = [(c, self.frame[c]) for c in self.frame.columns]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items)
        tm.assert_frame_equal(recons, self.frame)

        # pass some columns
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items, columns=['C', 'B', 'A'])
        tm.assert_frame_equal(recons, self.frame.loc[:, ['C', 'B', 'A']])

        # orient='index'

        row_items = [(idx, self.mixed_frame.xs(idx))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert recons['A'].dtype == np.float64

        msg = "Must pass columns with orient='index'"
        with pytest.raises(TypeError, match=msg):
            with tm.assert_produces_warning(FutureWarning,
                                            check_stacklevel=False):
                DataFrame.from_items(row_items, orient='index')

        # orient='index', but thar be tuples
        arr = construct_1d_object_array_from_listlike(
            [('bar', 'baz')] * len(self.mixed_frame))
        self.mixed_frame['foo'] = arr
        row_items = [(idx, list(self.mixed_frame.xs(idx)))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert isinstance(recons['foo'][0], tuple)

        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            rs = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
                                      orient='index',
                                      columns=['one', 'two', 'three'])
        xp = DataFrame([[1, 2, 3], [4, 5, 6]], index=['A', 'B'],
                       columns=['one', 'two', 'three'])
        tm.assert_frame_equal(rs, xp) 
Example #19
Source File: test_constructors.py    From twitter-stock-recommendation with MIT License 4 votes vote down vote up
def test_constructor_from_items(self):
        items = [(c, self.frame[c]) for c in self.frame.columns]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items)
        tm.assert_frame_equal(recons, self.frame)

        # pass some columns
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(items, columns=['C', 'B', 'A'])
        tm.assert_frame_equal(recons, self.frame.loc[:, ['C', 'B', 'A']])

        # orient='index'

        row_items = [(idx, self.mixed_frame.xs(idx))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert recons['A'].dtype == np.float64

        with tm.assert_raises_regex(TypeError,
                                    "Must pass columns with "
                                    "orient='index'"):
            with tm.assert_produces_warning(FutureWarning,
                                            check_stacklevel=False):
                DataFrame.from_items(row_items, orient='index')

        # orient='index', but thar be tuples
        arr = construct_1d_object_array_from_listlike(
            [('bar', 'baz')] * len(self.mixed_frame))
        self.mixed_frame['foo'] = arr
        row_items = [(idx, list(self.mixed_frame.xs(idx)))
                     for idx in self.mixed_frame.index]
        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            recons = DataFrame.from_items(row_items,
                                          columns=self.mixed_frame.columns,
                                          orient='index')
        tm.assert_frame_equal(recons, self.mixed_frame)
        assert isinstance(recons['foo'][0], tuple)

        with tm.assert_produces_warning(FutureWarning,
                                        check_stacklevel=False):
            rs = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6])],
                                      orient='index',
                                      columns=['one', 'two', 'three'])
        xp = DataFrame([[1, 2, 3], [4, 5, 6]], index=['A', 'B'],
                       columns=['one', 'two', 'three'])
        tm.assert_frame_equal(rs, xp)