[英]if conditions with a python panda data frame and plot with matplotlib
I would like to use some sort of if conditions to Plot only if the value of a specific column reaches a certain value.只有当特定列的值达到某个值时,我才想使用某种 if 条件来绘制。
Let's say in the example below I would like to plot only if the value of the cycle == 2.假设在下面的示例中,我只想在循环的值 == 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.如果我尝试这个,我会得到错误:ValueError: The truth value of a Series is ambiguous。 Use a.empty, a.bool(), a.item(), a.any() or a.all().
使用 a.empty、a.bool()、a.item()、a.any() 或 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.
有一个非常美好的一天。
In this line if df['cycle']==2
the df['cycle']
is returning a pandas series.在这一行中,
if df['cycle']==2
df['cycle']
返回一个 Pandas 系列。 When you compare this to 2
pandas doesn't know if you want to compare element wise, or the entire series, it is ambiguous.当您将其与
2
熊猫进行比较时,不知道您是要比较元素还是整个系列,这是模棱两可的。 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
在这里,您使用
df['cycle']
作为布尔系列来索引原始数据框并仅返回那些cycle
等于2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.