Skip to content

Commit a510291

Browse files
Backport PR #41897: BUG: to_hdf append string column to incompatible column (#42074)
Co-authored-by: lrepiton <[email protected]>
1 parent 4aa69fd commit a510291

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

doc/source/whatsnew/v1.3.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,7 @@ I/O
10801080
- Bug in the conversion from PyArrow to pandas (e.g. for reading Parquet) with nullable dtypes and a PyArrow array whose data buffer size is not a multiple of the dtype size (:issue:`40896`)
10811081
- Bug in :func:`read_excel` would raise an error when pandas could not determine the file type even though the user specified the ``engine`` argument (:issue:`41225`)
10821082
- Bug in :func:`read_clipboard` copying from an excel file shifts values into the wrong column if there are null values in first column (:issue:`41108`)
1083+
- Bug in :meth:`DataFrame.to_hdf` and :meth:`Series.to_hdf` raising a ``TypeError`` when trying to append a string column to an incompatible column (:issue:`41897`)
10831084

10841085
Period
10851086
^^^^^^

pandas/io/pytables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5000,7 +5000,7 @@ def _maybe_convert_for_string_atom(
50005000
# check for column in the values conflicts
50015001
if existing_col is not None:
50025002
eci = existing_col.validate_col(itemsize)
5003-
if eci > itemsize:
5003+
if eci is not None and eci > itemsize:
50045004
itemsize = eci
50055005

50065006
data_converted = data_converted.astype(f"|S{itemsize}", copy=False)

pandas/tests/io/pytables/test_append.py

+16
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,22 @@ def test_append_raise(setup_path):
778778
with pytest.raises(ValueError, match=msg):
779779
store.append("df", df)
780780

781+
# incompatible type (GH 41897)
782+
_maybe_remove(store, "df")
783+
df["foo"] = Timestamp("20130101")
784+
store.append("df", df)
785+
df["foo"] = "bar"
786+
msg = re.escape(
787+
"invalid combination of [values_axes] on appending data "
788+
"[name->values_block_1,cname->values_block_1,"
789+
"dtype->bytes24,kind->string,shape->(1, 30)] "
790+
"vs current table "
791+
"[name->values_block_1,cname->values_block_1,"
792+
"dtype->datetime64,kind->datetime64,shape->None]"
793+
)
794+
with pytest.raises(ValueError, match=msg):
795+
store.append("df", df)
796+
781797

782798
def test_append_with_timedelta(setup_path):
783799
# GH 3577

0 commit comments

Comments
 (0)