python-2.7 - python Pandas : set a value of column based on another value of a column in a list

标签 python-2.7 pandas dataframe

我有一个如下所示的数据框:

        f1              f2              class              n
0   weekly_return   0.155796               ab            weekly
1   monthly_return  0.153907               ab            monthly
2   volume_ratio    0.123844               NaN           volume
3   margin_selling_balance  0.115411       ad            margin
4   margin_debt_balance 0.107883           ae            margin
5   rv_ratio    0.077373                   NaN            rv
..................................................................

并且有一个名为 lst_n 的列表,如下所示:

lst_n = ['rv', 'ag', 'rg', ...........]

如果 n 的值在 lst_n 中,我想将此数据帧的类列的值设置为“class_a”。例如第五行,n 是 rv,位于 n 列表(lst_n)中,因此 class 的值设置为“class_a”。 我的代码如下,但有错误:

  lst_n = ['rv', 'ag', 'rg', ...........]
  df.loc[df.n is in lst_n, 'class'] = 'class_a'

但是有错误:

df.loc[df.n is in lst_n, 'class'] = 'class_a'
                           ^
SyntaxError: invalid syntax

谢谢!

最佳答案

您需要isin对于面具:

lst_n = ['rv', 'ag', 'rg']
df.loc[df['n'].isin(lst_n), 'class'] = 'class_a'
print (df)
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv

另一个解决方案 Series.mask :

df['class'] = df['class'].mask(df.n.isin(lst_n), 'class_a')
print (df)
                       f1        f2    class        n
0           weekly_return  0.155796       ab   weekly
1          monthly_return  0.153907       ab  monthly
2            volume_ratio  0.123844      NaN   volume
3  margin_selling_balance  0.115411       ad   margin
4     margin_debt_balance  0.107883       ae   margin
5                rv_ratio  0.077373  class_a       rv

关于python-2.7 - python Pandas : set a value of column based on another value of a column in a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44427554/

相关文章:

Python 2.7 : What does object. __setattr__ 在后台做什么?

python - 将计数器与列表列表一起使用

python-2.7 - 重命名多索引数据框中的索引值

python - 有没有办法在 Folium 中绘制许多标记?

python - 在 pandas 数据框中使用 for 循环迭代列

python - 在 dir() 中找出类型

python - 在循环中一次从列表中检索 2 个项目?

python - Pandas :尝试合并数据帧时获取 "TypeError: only integer scalar arrays can be converted to a scalar index"

python - 根据 Pandas 中的列名和位置选择列

在 R 中重新排序字母数字年龄组