Code Sample, a copy-pastable example if possible

df2[df2 > 0] = -df2

Problem description

In the 10-minute tutorial this code is used, which doesn't work as expected. The DataFrame contains a Nan value and positive and negative numeric values.

When running the code, an error appears:


TypeError Traceback (most recent call last) in () ----> 1 df2[df2 > 0] = -df2

c:\users\asfjhklmd\appdata\local\programs\python\python36-32\lib\site-packages\pandas\core\generic.py in neg(self) 1014 arr = operator.inv(values) 1015 else: -> 1016 arr = operator.neg(values) 1017 return self.array_wrap(arr) 1018

TypeError: bad operand type for unary -: 'str'

Expected Output

A DataFrame containing only negative values and a Nan value

Output of pd.show_versions()

INSTALLED VERSIONS ------------------ commit: None python: 3.6.4.final.0 python-bits: 32 OS: Windows OS-release: 10 machine: AMD64 processor: Intel64 Family 6 Model 58 Stepping 9, GenuineIntel byteorder: little LC_ALL: None LANG: None LOCALE: None.None pandas: 0.22.0 pytest: None pip: 9.0.1 setuptools: 28.8.0 Cython: None numpy: 1.14.0 scipy: 1.0.0 pyarrow: None xarray: None IPython: 6.2.1 sphinx: None patsy: 0.5.0 dateutil: 2.6.1 pytz: 2018.3 blosc: None bottleneck: None tables: None numexpr: None feather: None matplotlib: 2.1.2 openpyxl: None xlrd: None xlwt: None xlsxwriter: None lxml: None bs4: None html5lib: 1.0.1 sqlalchemy: None pymysql: None psycopg2: None jinja2: 2.10 s3fs: None fastparquet: None pandas_gbq: None pandas_datareader: None

Comment From: jorisvandenbossche

TypeError: bad operand type for unary -: 'str'

It seems you have string data in your dataframe, so it fails trying to get the negative of it.

If that was not the problem, can you be more explicit to what you see and what you expect, and provide a full reproducible example? (what is df2 ?) If you use the dataframe as defined in the docs, it does work correctly, as you can see in the output of both the stable and dev docs: http://pandas.pydata.org/pandas-docs/stable/10min.html#setting, http://pandas-docs.github.io/pandas-docs-travis/10min.html#setting (the code is run during doc build, and all values are negative, the single NaN was already there before, so is preserved)

Comment From: SonoDavid

Seems I inserted strings containing numerics in the last columns instead of the numerics themselves. Never mind. I'll close this issue...