2

I would like to use some sort of if conditions to Plot only if the value of a specific column reaches a certain value.

Let's say in the example below I would like to plot only if the value of the cycle == 2.

import pandas as pd
import matplotlib.pyplot as plt 

data = [('cycle',[1,1,2,2,3,3,4,4]),
         ('A',[0.1,0.5,0.2,0.6,0.15,0.43,0.13,0.59]),
         ('B',[ 500, 600, 510,580,512,575,499,598]),
         ]
df = pd.DataFrame.from_items(data)
#print(df)
x = df['A']
y = df['B']

if df['cycle']==2:
    plt.plot(x,y)

if I trie this, I got the fowlling error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Until now, I had no luck finding a way to solve the problem.

I am thankful for any help in regard to this Problem. Have a very nice day.

1 Answer 1

2

In this line if df['cycle']==2 the df['cycle'] is returning a pandas series. When you compare this to 2 pandas doesn't know if you want to compare element wise, or the entire series, it is ambiguous. What you could do instead is filter the table based on your condition, or filter the individual series. For example:

df = pd.DataFrame.from_items(data)
#print(df)
x = df.loc[df['cycle'] == 2, 'A']
y = df.loc[df['cycle'] == 2, 'B']

plt.plot(x,y)

Here you are using the df['cycle'] as a boolean series to index into the original data frame and return only those items where cycle is equal to 2

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.