0

I'm trying to manipulate date in a column by using for loop

my dataframe looks like this(under condition, the origianl dataframe has (104959 rows × 49 columns):

  WARNSIGN_TP        WARNSPEAK4DTL    WARNBEHAV4DTL    WARNEMOTION4DTL    WARNSIGN_DTL
0  1                  enthutiastic     running           energetic         Nan
1  1                  fillar words     Nan               happy             Nan
2  1                  motivated        moaning           sad               Nan
.
.
.

Here is my code:

for i in df.index:
    if (df.WARNSIGN_TP==1) & (df['WARNSIGN_DTL'].isnull):
        if df['WARNSPEAK4DTL'].isnull():
            df.at[i, 'WARNSIGN_DTL'] = '언어: ' + df.WARNSPEAK4DTL
        elif df['df.WARNBEHAV4DTL'].isnull():
            df.at[i, 'WARNSIGN_DTL'] = '행동: ' + df.WARNBEHAV4DTL
        elif df['WARNEMOTION4DTL'].isnull():
            df.at[i, 'WARNSIGN_DTL'] = '정서' + df.WARNEMOTION4DTL

In the code, I'm trying to correct Nan replace Nan values with additional string '언어: ','행동: ','정서: ' with values of WARNSPEAK4DTL,WARNBEHAV4DTL,WARNEMOTION4DTL columns under (df.WARNSIGN_TP==1) & (df['WARNSIGN_DTL'].isnull) this condition

And the output is:

TypeError                                 Traceback (most recent call last)
File ~\miniconda3\envs\py38\lib\site-packages\pandas\core\ops\array_ops.py:301, in na_logical_op(x, y, op)
    292 try:
    293     # For exposition, write:
    294     #  yarr = isinstance(y, np.ndarray)
   (...)
    299     # Then Cases where this goes through without raising include:
    300     #  (xint or xbool) and (yint or bool)
--> 301     result = op(x, y)
    302 except TypeError:

TypeError: unsupported operand type(s) for &: 'bool' and 'method'

During handling of the above exception, another exception occurred:

AssertionError                            Traceback (most recent call last)
Input In [74], in <cell line: 5>()
      4 # 경고신호: 언어, 행동, 정서 기타 상세 칼럼에서 구체적 기술에 필요한 내용을 따옵니다
      5 for row in df.itertuples():
----> 6     if (df.WARNSIGN_TP==1) & (df['WARNSIGN_DTL'].isnull):
      7         if df['WARNSPEAK4DTL'].isnull():
      8             df.at['WARNSIGN_DTL'] = '언어: ' + df.WARNSPEAK4DTL

File ~\miniconda3\envs\py38\lib\site-packages\pandas\core\ops\common.py:70, in _unpack_zerodim_and_defer.<locals>.new_method(self, other)
     66             return NotImplemented
     68 other = item_from_zerodim(other)
---> 70 return method(self, other)

File ~\miniconda3\envs\py38\lib\site-packages\pandas\core\arraylike.py:70, in OpsMixin.__and__(self, other)
     68 @unpack_zerodim_and_defer("__and__")
     69 def __and__(self, other):
---> 70     return self._logical_method(other, operator.and_)

File ~\miniconda3\envs\py38\lib\site-packages\pandas\core\series.py:5634, in Series._logical_method(self, other, op)
   5631 lvalues = self._values
   5632 rvalues = extract_array(other, extract_numpy=True, extract_range=True)
-> 5634 res_values = ops.logical_op(lvalues, rvalues, op)
   5635 return self._construct_result(res_values, name=res_name)

File ~\miniconda3\envs\py38\lib\site-packages\pandas\core\ops\array_ops.py:391, in logical_op(left, right, op)
    387 # For int vs int `^`, `|`, `&` are bitwise operators and return
    388 #   integer dtypes.  Otherwise these are boolean ops
    389 filler = fill_int if is_self_int_dtype and is_other_int_dtype else fill_bool
--> 391 res_values = na_logical_op(lvalues, rvalues, op)
    392 # error: Cannot call function of unknown type
    393 res_values = filler(res_values)  # type: ignore[operator]

File ~\miniconda3\envs\py38\lib\site-packages\pandas\core\ops\array_ops.py:311, in na_logical_op(x, y, op)
    308     result = libops.vec_binop(x.ravel(), y.ravel(), op)
    309 else:
    310     # let null fall thru
--> 311     assert lib.is_scalar(y)
    312     if not isna(y):
    313         y = bool(y)

AssertionError: 

I attach the solution that helped me to write the code: Update a dataframe in pandas while iterating row by row

the desired output should be like this:

   WARNSIGN_TP        WARNSPEAK4DTL    WARNBEHAV4DTL    WARNEMOTION4DTL    WARNSIGN_DTL
0  1                  enthutiastic     running           energetic         언어: enthutiastic 행동: running 정서: energetic
1  1                  fillar words     Nan               happy             언어: fillar words  정서: happy
2  1                  motivated        moaning           sad               언어: motivated 행동: moaning 정서: sad

1 Answers1

0

Just change

 df['WARNSIGN_DTL'].isnull

to

 df['WARNSIGN_DTL'].isnull()

(add parentheses)

  • `ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().` came up – Chung Joshua Oct 31 '22 at 06:33
  • ok that was the immediate syntactic issue.. now your condition doesn't look at the individual row (as you intended) but at the whole Series (of bool). Easiest should be to use the `.at[i, ...]` where you do `if (df.WARNSIGN_TP==1) & `. I.e. **df.at[i,** ] – almondandapricot Oct 31 '22 at 06:41
  • plus also **.at** is missing for the right side of the assignment, like `'정서' + df.WARNEMOTION4DTL`. But this loopy way may not be the intended/optimal way in pandas (I am not a pandas expert) – almondandapricot Oct 31 '22 at 06:44