internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: scikit-hep/awkward

Issue:
Constructing Array with different length columns should raise error
Creating an awkward Array from different length columns currently (in v1.1.1) just truncates to the length of the shortest column:
```
>>> ak.Array({"a": [1, 2], "b": [1, 2, 3]})
<Array [{a: 1, b: 1}, {a: 2, b: 2}] type='2 * {"a": int64, "b": int64}'>
```
I'm not sure if this is intended behaviour, but I personally would expect this to fail with an exception (for instance pandas gives a `ValueError: arrays must all be same length`). If there is a reason to have this as the behaviour, could it be included in the documentation, please?


Discussion:

Resolving patch:
diff --git a/src/awkward/highlevel.py b/src/awkward/highlevel.py
--- a/src/awkward/highlevel.py
+++ b/src/awkward/highlevel.py
@@ -230,9 +230,18 @@ def __init__(
         elif isinstance(data, dict):
             keys = []
             contents = []
+            length = None
             for k, v in data.items():
                 keys.append(k)
                 contents.append(Array(v).layout)
+                if length is None:
+                    length = len(contents[-1])
+                elif length != len(contents[-1]):
+                    raise ValueError(
+                        "dict of arrays in ak.Array constructor must have arrays "
+                        "of equal length ({0} vs {1})".format(length, len(contents[-1]))
+                        + ak._util.exception_suffix(__file__)
+                    )
             parameters = None
             if with_name is not None:
                 parameters = {"__record__": with_name}


Test patch:
diff --git a/tests/test_0381-fill-documentation-stubs-3.py b/tests/test_0381-fill-documentation-stubs-3.py
--- a/tests/test_0381-fill-documentation-stubs-3.py
+++ b/tests/test_0381-fill-documentation-stubs-3.py
@@ -8,7 +8,7 @@
 
 
 def test_pandas_style_constructor():
-    a = ak.Array({"x": [1, 2, 3, 4], "y": [[1, 2, 3], [], [4, 5]]})
+    a = ak.Array({"x": [1, 2, 3], "y": [[1, 2, 3], [], [4, 5]]})
     assert ak.to_list(a) == [
         {"x": 1, "y": [1, 2, 3]},
         {"x": 2, "y": []},
diff --git a/tests/test_0771-akArray-dict-constructor-require-equal-lengths.py b/tests/test_0771-akArray-dict-constructor-require-equal-lengths.py
new file mode 100644
--- /dev/null
+++ b/tests/test_0771-akArray-dict-constructor-require-equal-lengths.py
@@ -0,0 +1,12 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test():
+    with pytest.raises(ValueError):
+        ak.Array({"a": [1, 2], "b": [1, 2, 3]})
Repository: scikit-hep/awkward

Issue:
Invalid dimensionality from cartesian with zero length input
To reproduce
```python
import awkward as ak
data = ak.layout.NumpyArray([1, 2, 3])
data = ak.layout.ListArray64(ak.layout.Index64([0]), ak.layout.Index64([3]), data)
data = ak.layout.IndexedArray64(ak.layout.Index64([]), data)
cart = ak.cartesian([data, data])
print(cart.type)
```
This prints `0 * var * (1 * int64, int64)`. I think it should be `0 * var * (int64, int64)`.
If you compare this to the case that the index of the `IndexedArray64` has one entry, you nicely get `1 * var * (int64, int64)`.
I run into invalid array shapes with this behavior, as `ak.unzip(cart)[0]` suddenly is 3 dimensional (in case of 0 length input) instead of 2 dimensional.

Tested on latest git main (awkward-1.2.0rc4)



Discussion:

Resolving patch:
diff --git a/src/awkward/operations/structure.py b/src/awkward/operations/structure.py
--- a/src/awkward/operations/structure.py
+++ b/src/awkward/operations/structure.py
@@ -3073,6 +3073,13 @@ def apply(x, i):
 
         def getfunction3(inputs, depth):
             if depth == posaxis + len(new_arrays):
+                if all(len(x) == 0 for x in inputs):
+                    inputs = [
+                        x.content
+                        if isinstance(x, ak.layout.RegularArray) and x.size == 1
+                        else x
+                        for x in inputs
+                    ]
                 return lambda: (
                     ak.layout.RecordArray(inputs, recordlookup, parameters=parameters),
                 )


Test patch:
diff --git a/tests/test_0794-ak-cartesian-on-empty-array.py b/tests/test_0794-ak-cartesian-on-empty-array.py
new file mode 100644
--- /dev/null
+++ b/tests/test_0794-ak-cartesian-on-empty-array.py
@@ -0,0 +1,25 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test():
+    nparray = ak.layout.NumpyArray(np.array([1, 2, 3], dtype=np.int64))
+    listarray = ak.layout.ListArray64(
+        ak.layout.Index64(np.array([0], dtype=np.int64)),
+        ak.layout.Index64(np.array([3], dtype=np.int64)),
+        nparray,
+    )
+    indexedarray = ak.layout.IndexedArray64(ak.layout.Index64([]), listarray)
+
+    cart = ak.cartesian([indexedarray, indexedarray], nested=True)
+    assert str(cart.type) == "0 * var * var * (int64, int64)"
+    assert ak.to_list(cart) == []
+
+    cart = ak.cartesian([indexedarray, indexedarray], nested=False)
+    assert str(cart.type) == "0 * var * (int64, int64)"
+    assert ak.to_list(cart) == []
Repository: scikit-hep/awkward

Issue:
`ak.is_none` returns NumpyArray as-is
Reproducer:
```python
>>> import awkward as ak
>>> ak.is_none(np.arange(12))
<Array [0, 1, 2, 3, 4, 5, ... 7, 8, 9, 10, 11] type='12 * int64'>
```

I assume that the cause is [this final `else` clause](https://github.com/scikit-hep/awkward-1.0/blob/4aaae9a4ddbff3b42d633b38d07f047794463d62/src/awkward/operations/structure.py#L2546-L2558), which is visited as `NumpyArray` is not considered by the `zeros` case. I would assume the solution is just to add another type to the `isinstance` call?

Version Info
```python
>>> import awkward as ak
>>> ak.__version__
ak.__version__
```



Discussion:

Resolving patch:
diff --git a/src/awkward/operations/structure.py b/src/awkward/operations/structure.py
--- a/src/awkward/operations/structure.py
+++ b/src/awkward/operations/structure.py
@@ -2549,6 +2549,7 @@ def getfunction(layout, depth, posaxis):
                     ak._util.unknowntypes,
                     ak._util.listtypes,
                     ak._util.recordtypes,
+                    ak.layout.NumpyArray,
                 ),
             ):
                 return lambda: ak.layout.NumpyArray(


Test patch:
diff --git a/tests/test_0863-is-none-numpy-array.py b/tests/test_0863-is-none-numpy-array.py
new file mode 100644
--- /dev/null
+++ b/tests/test_0863-is-none-numpy-array.py
@@ -0,0 +1,22 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test_numpy_array():
+    x = np.arange(12)
+    y = ak.is_none(x)
+
+    assert y.tolist() == [False] * 12
+
+
+def test_awkward_from_numpy_array():
+    x = np.arange(12)
+    y = ak.from_numpy(x)
+    z = ak.is_none(y)
+
+    assert z.tolist() == [False] * 12
Repository: scikit-hep/awkward

Issue:
`ak.from_parquet` lazy loading does not consider `columns` arg early enough
When using `ak.from_parquet()` with `lazy=True` the function seems to take a different code path that ignores the `columns` argument in the early stages. Not sure if this is a bug or intended behavior because `ak.layout.VirtualArray` requires it (but then it seems to be undocumented - apart from datetime fields generally not supported)?

The following fails (a particularly useful example to exclude fields of yet (#835 🎉 ) unsupported datatypes):
```python
>>> import awkward as ak
>>> ak.__version__
'1.2.3'
>>> example_df_with_datetime_col = pd.DataFrame({
             'timestamp': [1621164368000000000],
             'datetime': [pd.to_datetime(1621164368000000000)]
})
>>> example_df_with_datetime_col.to_parquet('table_with_datetime_col.parquet')
>>> ak.from_parquet('table_with_datetime_col.parquet', columns=['timestamp'], lazy=True)

ValueError: cannot convert NumPy dtype with kind M into a NumpyForm
(https://github.com/scikit-hep/awkward-1.0/blob/1.2.3/src/libawkward/Content.cpp#L232)

# in contrast:
>>> ak.from_parquet('table_with_datetime_col.parquet', columns=['timestamp'])  # works as expected
>>> ak.from_parquet('table_with_datetime_col.parquet')  # fails as expected
ValueError: cannot include dtype 'M' in a buffer
```



Discussion:
Is the only unsupported field type datetime and timedelta? If so, then #835 would solve it. Nevertheless, I can check to see if it's building Forms for columns that aren't in the requested set of columns and prevent that, since they won't be used later. Thanks for catching this.

Resolving patch:
diff --git a/src/awkward/operations/convert.py b/src/awkward/operations/convert.py
--- a/src/awkward/operations/convert.py
+++ b/src/awkward/operations/convert.py
@@ -3596,12 +3596,15 @@ def from_parquet(
 
     if columns is None:
         columns = all_columns
+    pa_fields = []
     for x in columns:
         if x not in all_columns:
             raise ValueError(
                 "column {0} not found in schema".format(repr(x))
                 + ak._util.exception_suffix(__file__)
             )
+        pa_fields.append(schema.field(x))
+    schema = pyarrow.schema(pa_fields)
 
     if len(row_groups) == 0:
         out = ak.layout.RecordArray(


Test patch:
Repository: scikit-hep/awkward

Issue:
Typo in `identifier.py`
https://github.com/scikit-hep/awkward-1.0/blob/a0ec3bcacacc81a47fe61a1d99b0bc512a8bb3cf/src/awkward/_v2/identifier.py#L30


Discussion:

Resolving patch:
diff --git a/src/awkward/_v2/identifier.py b/src/awkward/_v2/identifier.py
--- a/src/awkward/_v2/identifier.py
+++ b/src/awkward/_v2/identifier.py
@@ -27,7 +27,7 @@ def __init__(self, ref, fieldloc, data):
 
         self._data = self._nplike.asarray(data, order="C")
         if len(self._data.shape) != 2:
-            raise TypeError("Identifer data must be 2-dimensional")
+            raise TypeError("Identifier data must be 2-dimensional")
 
         # TypeError for unsupported types?
         self._T = self._data.dtype


Test patch:
Repository: scikit-hep/awkward

Issue:
`ak.packed` doesn't truncate the contents of `ListOffsetArray`
```python3
For example, this layout
>>> content = ak.layout.NumpyArray(
...     np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9])
... )
>>> offsets = ak.layout.Index64(np.array([0, 3, 3, 5, 6]))
>>> layout = ak.layout.ListOffsetArray64(offsets, content)
```
Produces this when packed
```python3
>>> packed = ak.packed(layout, highlevel=False)
>>> packed.content
<NumpyArray format="d" shape="9" data="1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9" at="0x000001b74f90"/>
```
when it should be
```python3
>>> packed.content
<NumpyArray format="d" shape="6" data="1.1 2.2 3.3 4.4 5.5 6.6" at="0x0000017d2f90"/>
```


Discussion:

Resolving patch:
diff --git a/src/awkward/operations/structure.py b/src/awkward/operations/structure.py
--- a/src/awkward/operations/structure.py
+++ b/src/awkward/operations/structure.py
@@ -2226,9 +2226,10 @@ def apply(layout, depth, posaxis):
             ),
         ):
             new_layout = layout.toListOffsetArray64(True)
+            new_length = new_layout.offsets[-1]
             return ak.layout.ListOffsetArray64(
                 new_layout.offsets,
-                apply(new_layout.content, depth + 1, posaxis),
+                apply(truncate(new_layout.content, new_length), depth + 1, posaxis),
                 new_layout.identities,
                 new_layout.parameters,
             )


Test patch:
diff --git a/tests/test_0912-packed.py b/tests/test_0912-packed.py
--- a/tests/test_0912-packed.py
+++ b/tests/test_0912-packed.py
@@ -71,6 +71,7 @@ def test_list_offset_array():
     assert ak.to_list(packed) == ak.to_list(layout)
     assert isinstance(packed, ak.layout.ListOffsetArray64)
     assert packed.offsets[0] == 0
+    assert len(packed.content) == packed.offsets[-1]
 
 
 def test_unmasked_array():
Repository: scikit-hep/awkward

Issue:
`ak.flatten` fails to flatten `ak.layout.NumpyArray` for `axis=None`
Completely flattening an n-D `ak.layout.NumpyArray` doesn't produce a flat layout:

```python3
>>> import awkward as ak
>>> import numpy as np
>>> ak.flatten(ak.from_numpy(np.zeros((3, 3, 5))), axis=None)
<Array [[[0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]]] type='3 * 3 * 5 * float64'>
```
`ak.flatten` fails to flatten `ak.layout.NumpyArray` for `axis=None`
Completely flattening an n-D `ak.layout.NumpyArray` doesn't produce a flat layout:

```python3
>>> import awkward as ak
>>> import numpy as np
>>> ak.flatten(ak.from_numpy(np.zeros((3, 3, 5))), axis=None)
<Array [[[0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]]] type='3 * 3 * 5 * float64'>
```


Discussion:

Resolving patch:
diff --git a/src/awkward/_util.py b/src/awkward/_util.py
--- a/src/awkward/_util.py
+++ b/src/awkward/_util.py
@@ -571,9 +571,14 @@ def completely_flatten(array):
 
     elif isinstance(array, ak.layout.NumpyArray):
         if array.format.upper().startswith("M"):
-            return (ak.nplike.of(array).asarray(array.view_int64).view(array.format),)
+            return (
+                ak.nplike.of(array)
+                .asarray(array.view_int64)
+                .view(array.format)
+                .reshape(-1),
+            )
         else:
-            return (ak.nplike.of(array).asarray(array),)
+            return (ak.nplike.of(array).asarray(array).reshape(-1),)
 
     else:
         raise RuntimeError(


Test patch:
diff --git a/tests/test_0973-flatten-multidimensional-numpy-array.py b/tests/test_0973-flatten-multidimensional-numpy-array.py
new file mode 100644
--- /dev/null
+++ b/tests/test_0973-flatten-multidimensional-numpy-array.py
@@ -0,0 +1,13 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test():
+    array = ak.from_numpy(np.zeros((3, 3, 5)))
+    flattened = ak.flatten(array, axis=None)
+    assert flattened.ndim == 1
Repository: scikit-hep/awkward

Issue:
`ak.mask` fails for n-dim `NumpyArray` masks
The following example raises a `ValueError`
```python3

import awkward as ak
import numpy as np

array = ak.Array(
    ak.layout.RegularArray(ak.layout.NumpyArray(np.r_[1, 2, 3, 4, 5, 6, 7, 8, 9]), 3)
)
mask = ak.Array(ak.layout.NumpyArray(np.array([
    [True, True, True],
    [True, True, False],
    [True, False, True]
])))

ak.mask(array, mask)
```
`ak.mask` fails for n-dim `NumpyArray` masks
The following example raises a `ValueError`
```python3

import awkward as ak
import numpy as np

array = ak.Array(
    ak.layout.RegularArray(ak.layout.NumpyArray(np.r_[1, 2, 3, 4, 5, 6, 7, 8, 9]), 3)
)
mask = ak.Array(ak.layout.NumpyArray(np.array([
    [True, True, True],
    [True, True, False],
    [True, False, True]
])))

ak.mask(array, mask)
```


Discussion:

Resolving patch:
diff --git a/src/awkward/operations/structure.py b/src/awkward/operations/structure.py
--- a/src/awkward/operations/structure.py
+++ b/src/awkward/operations/structure.py
@@ -179,6 +179,7 @@ def getfunction(inputs):
         [layoutarray, layoutmask],
         getfunction,
         behavior,
+        numpy_to_regular=True,
         right_broadcast=False,
         pass_depth=False,
     )


Test patch:
diff --git a/tests/test_0975-mask-multidimensional-numpy-array.py b/tests/test_0975-mask-multidimensional-numpy-array.py
new file mode 100644
--- /dev/null
+++ b/tests/test_0975-mask-multidimensional-numpy-array.py
@@ -0,0 +1,22 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test():
+    array = ak.Array(
+        ak.layout.RegularArray(
+            ak.layout.NumpyArray(np.r_[1, 2, 3, 4, 5, 6, 7, 8, 9]), 3
+        )
+    )
+    mask = ak.Array(
+        ak.layout.NumpyArray(
+            np.array([[True, True, True], [True, True, False], [True, False, True]])
+        )
+    )
+
+    assert ak.mask(array, mask).to_list() == [[1, 2, 3], [4, 5, None], [7, None, 9]]
Repository: scikit-hep/awkward

Issue:
`ak.where` fails for n-dim `NumpyArray` conditions
Given the following n-dim `NumpyArray` condition, `ak.where` raises a `ValueError` (similar to #975)
```python3
array = ak.Array(
    ak.layout.RegularArray(
        ak.layout.NumpyArray(np.r_[1, 2, 3, 4, 5, 6, 7, 8, 9]), 3
    )
)
mask = ak.Array(
    ak.layout.NumpyArray(
        np.array([[True, True, True], [True, True, False], [True, False, True]])
    )
)

assert ak.where(mask == 2, array, 2 * array).tolist() == [
    [2, 4, 6], 
    [8, 10, 12],  
    [14, 16, 18]
]
```



Discussion:

Resolving patch:
diff --git a/src/awkward/operations/structure.py b/src/awkward/operations/structure.py
--- a/src/awkward/operations/structure.py
+++ b/src/awkward/operations/structure.py
@@ -1728,7 +1728,11 @@ def getfunction(inputs):
 
         behavior = ak._util.behaviorof(akcondition, left, right)
         out = ak._util.broadcast_and_apply(
-            [akcondition, left, right], getfunction, behavior, pass_depth=False
+            [akcondition, left, right],
+            getfunction,
+            behavior,
+            pass_depth=False,
+            numpy_to_regular=True,
         )
 
         return ak._util.maybe_wrap(out[0], behavior, highlevel)


Test patch:
diff --git a/tests/test_0979-where-multidimensional-numpy-array.py b/tests/test_0979-where-multidimensional-numpy-array.py
new file mode 100644
--- /dev/null
+++ b/tests/test_0979-where-multidimensional-numpy-array.py
@@ -0,0 +1,26 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test():
+    array = ak.Array(
+        ak.layout.RegularArray(
+            ak.layout.NumpyArray(np.r_[1, 2, 3, 4, 5, 6, 7, 8, 9]), 3
+        )
+    )
+    condition = ak.Array(
+        ak.layout.NumpyArray(
+            np.array([[True, True, True], [True, True, False], [True, False, True]])
+        )
+    )
+
+    assert ak.where(condition == 2, array, 2 * array).tolist() == [
+        [2, 4, 6],
+        [8, 10, 12],
+        [14, 16, 18],
+    ]
Repository: scikit-hep/awkward

Issue:
ak.fill_none is losing the dtype of its replacement value
```python
>>> array = ak.values_astype(ak.Array([1.1, 2.2, None, 3.3]), np.float32)
>>> array
<Array [1.1, 2.2, None, 3.3] type='4 * ?float32'>
>>> ak.fill_none(array, np.float32(0))
<Array [1.1, 2.2, 0, 3.3] type='4 * float64'>
```

But if we explicitly make the fill value a `np.float32(0)`, we want the output to be `float32`.

Awkward Array knows the NumPy type coercion rules, which would merge `float32` and `float32` to make `float32` (not `float64`). For example,

```python
>>> ak.concatenate([array, np.array([1, 2, 3], np.float32)])
<Array [1.1, 2.2, None, 3.3, 1, 2, 3] type='7 * ?float32'>
```


Discussion:

Resolving patch:
diff --git a/src/awkward/operations/structure.py b/src/awkward/operations/structure.py
--- a/src/awkward/operations/structure.py
+++ b/src/awkward/operations/structure.py
@@ -2719,7 +2719,14 @@ def fill_none(array, value, axis=ak._util.MISSING, highlevel=True, behavior=None
             )
 
     # Convert value type to appropriate layout
-    if (
+    if isinstance(value, (bool, numbers.Number, np.bool_, np.number)) or (
+        isinstance(value, np.ndarray)
+        and issubclass(value.dtype.type, (np.bool_, np.number))
+    ):
+        valuelayout = ak.operations.convert.to_layout(
+            nplike.asarray(value), allow_record=False, allow_other=False
+        )
+    elif (
         isinstance(value, Iterable)
         and not (
             isinstance(value, (str, bytes))


Test patch:
diff --git a/tests/test_0546-fill_none-replacement-value-type.py b/tests/test_0546-fill_none-replacement-value-type.py
new file mode 100644
--- /dev/null
+++ b/tests/test_0546-fill_none-replacement-value-type.py
@@ -0,0 +1,12 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test():
+    array = ak.values_astype(ak.Array([1.1, 2.2, None, 3.3]), np.float32)
+    assert str(ak.fill_none(array, np.float32(0)).type) == "4 * float32"
Repository: scikit-hep/awkward

Issue:
`ak.packed` fails for `RegularArray` with size 0
### Version of Awkward Array

1.4.0

### Description and code to reproduce

Given this code
```python3
ak.packed(ak.from_numpy(np.zeros((1, 0), dtype=np.int32), regulararray=True))
```
`ak.packed` raises `ZeroDivisionError` when dividing the length of the content by the size.


Discussion:

Resolving patch:
diff --git a/src/awkward/operations/structure.py b/src/awkward/operations/structure.py
--- a/src/awkward/operations/structure.py
+++ b/src/awkward/operations/structure.py
@@ -2174,7 +2174,10 @@ def _pack_layout(layout):
         new_index[~is_none] = nplike.arange(len(new_index) - nplike.sum(is_none))
 
         return ak.layout.IndexedOptionArray64(
-            ak.layout.Index64(new_index), layout.project()
+            ak.layout.Index64(new_index),
+            layout.project(),
+            layout.identities,
+            layout.parameters,
         )
 
     # Project indexed arrays
@@ -2212,7 +2215,9 @@ def _pack_layout(layout):
 
     # UnmaskedArray just wraps another array
     elif isinstance(layout, ak.layout.UnmaskedArray):
-        return ak.layout.UnmaskedArray(layout.content)
+        return ak.layout.UnmaskedArray(
+            layout.content, layout.identities, layout.parameters
+        )
 
     # UnionArrays can be simplified
     # and their contents too
@@ -2262,13 +2267,20 @@ def _pack_layout(layout):
 
         content = layout.content
 
-        # Truncate content if it is larger than a perfect
-        # multiple of the RegularArray size
-        n, r = divmod(len(content), layout.size)
-        if r != 0:
-            content = content[: n * layout.size]
+        # Truncate content to perfect multiple of the RegularArray size
+        if layout.size > 0:
+            r = len(content) % layout.size
+            content = content[: len(content) - r]
+        else:
+            content = content[:0]
 
-        return ak.layout.RegularArray(content, layout.size)
+        return ak.layout.RegularArray(
+            content,
+            layout.size,
+            len(layout),
+            layout.identities,
+            layout.parameters,
+        )
 
     # BitMaskedArrays can change length
     elif isinstance(layout, ak.layout.BitMaskedArray):


Test patch:
diff --git a/tests/test_1006-packed-regular-array-zero-size.py b/tests/test_1006-packed-regular-array-zero-size.py
new file mode 100644
--- /dev/null
+++ b/tests/test_1006-packed-regular-array-zero-size.py
@@ -0,0 +1,13 @@
+# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
+
+from __future__ import absolute_import
+
+import pytest  # noqa: F401
+import numpy as np  # noqa: F401
+import awkward as ak  # noqa: F401
+
+
+def test():
+    array = ak.from_numpy(np.zeros((1, 0), dtype=np.int32), regulararray=True)
+    packed = ak.packed(array)
+    assert ak.to_list(packed) == [[]]