【问题标题】:Update column depending if other column value is in list更新列取决于其他列值是否在列表中
【发布时间】:2022-11-10 19:51:37
【问题描述】:

我正在处理需要手动清理的数据集。 我需要做的一件事是在一列中为我的某些行分配某个值,如果在另一列中,该行的值存在于我定义的列表中。

所以这里是我想做的一个简化的例子:

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

因此,所需的修改后的 Dataframe 如下所示:

  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

这只会改变 col2 并且显然只有带有硬编码标签'b' 的行。

我也试过:

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 <cell line: 4>()
      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().

谢谢你的帮助 !

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    像这样使用numpy.where

    import numpy as np
    to_be_changed = ['b','e','a']
    
    df = pd.DataFrame({'col1':[1,2,2,1,2],'col2':['a','b','c','d','e' ]})
    
    df["col1"] = np.where(df["col2"].isin(to_be_changed), 3, df["col1"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      相关资源
      最近更新 更多