Одна вещь, которую мне нужно сделать, это присвоить определенное значение в одном столбце некоторым из моих строк, если в другом столбце эта строка имеет значение он присутствует в списке, который я определил.
Итак, вот сокращенный пример того, что я хочу сделать:
Код: Выделить всё
to_be_changed = ['b','e','a']
df = pd.DataFrame({'col1':[1,2,2,1,2],'col2':['a','b','c','d','e' ]})
# change col1 in all rows which label shows up in to_be_changed to 3
Код: Выделить всё
col1 col2
0 3 a
1 3 b
2 2 c
3 1 d
4 3 e
Код: Выделить всё
df = pd.DataFrame(np.where(df=='b' ,3,df)
,index=df.index,columns=df.columns)
Код: Выделить всё
col1 col2
0 1 a
1 2 3
2 2 c
3 1 d
4 2 e
Я также пробовал:
p>
Код: Выделить всё
df = pd.DataFrame(np.where(df in to_be_changed ,3,df)
,index=df.index,columns=df.columns)
Код: Выделить всё
ValueError Traceback (most recent call last)
/tmp/ipykernel_11084/574679588.py in ()
3 df = pd.DataFrame({'col1':[1,2,2,1,2],'col2':['a','b','c','d','e' ]})
4 df = pd.DataFrame(
----> 5 np.where(df in to_be_changed ,3,df)
6 ,index=df.index,columns=df.columns)
7 df
~/.local/lib/python3.9/site-packages/pandas/core/generic.py in __nonzero__(self)
1525 @final
1526 def __nonzero__(self):
-> 1527 raise ValueError(
1528 f"The truth value of a {type(self).__name__} is ambiguous. "
1529 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Подробнее здесь: https://stackoverflow.com/questions/742 ... is-in-list
Мобильная версия