Conditionally set pandas dataframe column values

后端 未结 1 1849
无人及你
无人及你 2021-01-23 05:57

This question is exactly as the following request, with one more twist,

  • Pandas: Replacing column values in dataframe
  • Conditional Substitution of values i
相关标签:
1条回答
  • 2021-01-23 06:24

    You can use square brackets to access a column name using the string rather than as an attribute, I also strongly recommend that you ditch this habit of accessing columns by attribute as this can lead to confusing behaviour such as if you have a column name sum and you do df.sum will return the address of the method sum rather than the column 'sum'.

    So df[Col] = df[Col] + 1

    will work so long as the column name exists.

    Regarding your 2nd question, to compare an array against a scalar value use the bitwise operators &, | and ~ for and, or and not respectively these will return an array of boolean values, to use more than 1 condition you need to wrap the conditions in parentheses due to operator precedence as & has higher precedence than the comparison operators.

    So:

    df[(df[col] >=.25) & (df[col] <= .35)]
    

    should work, this will mask the df to only the rows where both conditions are met

    0 讨论(0)
提交回复
热议问题