FIltering rows and appending values

Viewed 225

I want to filter a dataframe and append a value to a new/existing column in the dataframe. For example in the following dataframe, I want to append a value of 0.7 to column pre-mean where the month values are equal to 11. So in other words pre_mean column should contain values of 0.7 at rows 2 to 5 while all other columns should have a NaN value.

I tried something like this, but of course it's incorrect.

df[:pre_mean] = ifelse.(df[:month] .== 11, 0.7, df)

In python, you can do this using pd.apply or np.where functions,

#How to do in python
df["pre_mean"] = np.where(df["month"] == 11, 0.7, None)

But I have got no clue how to achieve this in Julia? Any Ideas?

enter image description here

2 Answers
df[df.month .== 11, :pre_mean] .= 0.7

This should work.

Also the answer in the question is almost correct:

df.pre_mean .= ifelse.(df.month .== 11, 0.7, df.premean)

which should be faster than the solution proposed by @Andy_101 (which is also correct) as it does not allocate.

As a side note observe that df[:pre_mean] is not allowed in DataFrames.jl. Data frame is a 2-dimensional object so you have to pass both row and column selector (unless you use a getproperty method like in the answer of @Andy_101 and mine).

Related