Skip to content

BUG: "ValueError: Must provide strings." when using "string" as dtype #42918

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
2 of 3 tasks
omgMath opened this issue Aug 6, 2021 · 6 comments
Closed
2 of 3 tasks

BUG: "ValueError: Must provide strings." when using "string" as dtype #42918

omgMath opened this issue Aug 6, 2021 · 6 comments
Labels
Bug Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate Strings String extension data type and string data

Comments

@omgMath
Copy link

omgMath commented Aug 6, 2021

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

Given a csv file test.csv(sorry, didn't manage to reproduce without reading a csv) with the following content:

x,y
00000114136524405793555657657729584885,
df = pd.read_csv('test.csv', dtype={'x': 'string', 'y': 'string'})
df['y'].fillna({}, inplace=True)

Problem description

Above code fails with an error ValueError: Must provide strings.. Full traceback below in the details.

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    df['y'].fillna({}, inplace=True)
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/series.py", line 4529, in fillna
    return super().fillna(
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/generic.py", line 6057, in fillna
    new_data = self._mgr.fillna(
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/internals/managers.py", line 585, in fillna
    return self.apply(
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/internals/managers.py", line 406, in apply
    applied = getattr(b, f)(**kwargs)
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/internals/blocks.py", line 1779, in fillna
    values = values.fillna(value=value, limit=limit)
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/arrays/string_.py", line 262, in fillna
    return super().fillna(value, method, limit)
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/arrays/numpy_.py", line 307, in fillna
    new_values[mask] = value
  File "/home/user/.local/lib/python3.8/site-packages/pandas/core/arrays/string_.py", line 256, in __setitem__
    raise ValueError("Must provide strings.")
ValueError: Must provide strings.

On the other hand, when the dtype object is {'x': str, 'y': str}, the error is not raised - from the docs I understood both versions should be equivalent?

Expected Output

Both versions have the same behavior.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : c7f7443
python : 3.8.10.final.0
python-bits : 64
OS : Linux
OS-release : 5.11.0-25-generic
Version : #27~20.04.1-Ubuntu SMP Tue Jul 13 17:41:23 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.3.1
numpy : 1.21.1
pytz : 2021.1
dateutil : 2.8.2
pip : 21.2.2
setuptools : 44.0.0
Cython : None
pytest : 6.2.4
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : 2021.07.0
fastparquet : None
gcsfs : 2021.07.0
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None
None

@omgMath omgMath added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 6, 2021
@lithomas1
Copy link
Member

They are not. str is object dtype and string is our new StringDtype. Sorry for the confusion.

I think the error you are getting is because StringArrays cannot be created from a numpy array with nans. Haven't looked in depth closely though.

@omgMath
Copy link
Author

omgMath commented Aug 7, 2021

Oh, sorry then.
Is this something you want to look at anyways or should I close it?

@lithomas1
Copy link
Member

I'll take a closer look soon. Will keep you updated.

@mroeschke mroeschke added Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate Strings String extension data type and string data and removed Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 21, 2021
@HansBambel
Copy link

HansBambel commented Apr 4, 2022

I get the same error message when I use df.replace(r"^replaceme", np.nan, regex=True) with the pandas StringDtype. It works for dtype "str".

@jorisvandenbossche
Copy link
Member

I get the same error message when I use df.replace(r"^replaceme", np.nan, regex=True) with the pandas StringDtype. It works for dtype "str".

@HansBambel This has been fixed in the meantime (testing with pandas 2.2.3):

In [18]: ser = pd.Series(["a", "b", "c"], dtype="string")

In [19]: ser.replace(r"^a", np.nan, regex=True)
Out[19]: 
0    <NA>
1       b
2       c
dtype: string

(the NaN gets converted to the missing value sentinel for the string dtype)

Above code fails with an error ValueError: Must provide strings.. Full traceback below in the details.

@omgMath It seems that this no longer raises as well. Not sure what changed, but it seems we no longer treat {} (empty dict) as the value to replace with (also with object dtype, we don't actually fill in the {}):

In [33]: ser = pd.Series(["a", None], dtype="string")

In [34]: ser.fillna({})
Out[34]: 
0       a
1    <NA>
dtype: string

In [35]: ser = pd.Series(["a", None], dtype="object")

In [36]: ser.fillna({})
Out[36]: 
0       a
1    None
dtype: object

@jorisvandenbossche
Copy link
Member

Going to close this issue, because I think replacing with np.nan is certainly tested nowadays, and also replacing with an empty dict is already tested in test_replace_with_empty_dictlike

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Bug Missing-data np.nan, pd.NaT, pd.NA, dropna, isnull, interpolate Strings String extension data type and string data
Projects
None yet
Development

No branches or pull requests

5 participants