| 4145 | |
| 4146 | |
| 4147 | def test_dictionary_with_pandas(): |
| 4148 | src_indices = np.repeat([0, 1, 2], 2) |
| 4149 | dictionary = np.array(['foo', 'bar', 'baz'], dtype=object) |
| 4150 | mask = np.array([False, False, True, False, False, False]) |
| 4151 | |
| 4152 | for index_type in ['uint8', 'int8', 'uint16', 'int16', 'uint32', 'int32', |
| 4153 | 'uint64', 'int64']: |
| 4154 | indices = src_indices.astype(index_type) |
| 4155 | d1 = pa.DictionaryArray.from_arrays(indices, dictionary) |
| 4156 | d2 = pa.DictionaryArray.from_arrays(indices, dictionary, mask=mask) |
| 4157 | |
| 4158 | pandas1 = d1.to_pandas() |
| 4159 | # Pandas Categorical uses signed int codes. Arrow converts: |
| 4160 | # uint8 to int16, uint16 to int32, uint32 and uint64 to int64, signed unchanged |
| 4161 | if index_type == 'uint8': |
| 4162 | compare_indices = indices.astype('int16') |
| 4163 | elif index_type == 'uint16': |
| 4164 | compare_indices = indices.astype('int32') |
| 4165 | elif index_type in ('uint32', 'uint64'): |
| 4166 | compare_indices = indices.astype('int64') |
| 4167 | else: |
| 4168 | compare_indices = indices |
| 4169 | ex_pandas1 = pd.Categorical.from_codes(compare_indices, categories=dictionary) |
| 4170 | |
| 4171 | tm.assert_series_equal(pd.Series(pandas1), pd.Series(ex_pandas1)) |
| 4172 | |
| 4173 | pandas2 = d2.to_pandas() |
| 4174 | assert pandas2.isnull().sum() == 1 |
| 4175 | |
| 4176 | # Use same conversion as above for comparison |
| 4177 | if index_type == 'uint8': |
| 4178 | signed_indices = indices.astype('int16') |
| 4179 | elif index_type == 'uint16': |
| 4180 | signed_indices = indices.astype('int32') |
| 4181 | elif index_type in ('uint32', 'uint64'): |
| 4182 | signed_indices = indices.astype('int64') |
| 4183 | else: |
| 4184 | signed_indices = indices |
| 4185 | ex_pandas2 = pd.Categorical.from_codes(np.where(mask, -1, |
| 4186 | signed_indices), |
| 4187 | categories=dictionary) |
| 4188 | |
| 4189 | tm.assert_series_equal(pd.Series(pandas2), pd.Series(ex_pandas2)) |
| 4190 | |
| 4191 | |
| 4192 | def random_strings(n, item_size, pct_null=0, dictionary=None): |