Home > Software engineering >  Dataframe column to list if other column is positive
Dataframe column to list if other column is positive

Time:07-11

I want to convert a dataframe column to a list containing only values if another column has positive values.

Word Value Another Column
First 2 1
Second 15 2
Third -5 30
Fourth 10 22

The resulting list should look like this:

[First, Second, Fourth]

CodePudding user response:

Assuming your dataframe is named df you can first filter it then select the column Word:

filtered_df = df[df["Value"] >= 0]
word_list = filtered_df["Word"].values

CodePudding user response:

You can filter the dataframe by the "Value > 0" then take word column values :

 df[df["value"] > 0]["word"].tolist()

CodePudding user response:

Mask the DataFrame with the condition you want match. Second take the view of the DataFrame and return this as list.

df = pd.DataFrame({'x': np.arange(5), 
                   'y': np.arange(5)-2.5})
mask = df.y > 0  # create mask
df.x[mask].to_list()
  • Related