使用条件列绘制 Pandas DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36036274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
plot pandas DataFrame with condition columns
提问by rkjt50r983
I have this kind of pandas.DataFrame. "a","b" are conditions when getting "x" and "y".
我有这种pandas.DataFrame。"a","b" 是获取 "x" 和 "y" 时的条件。
df = pd.DataFrame([[10,20,0,.1], [10,20,1,.5], [100,200,0,.33], [100,200,1,.11]], columns=["a", "b", "x", "y"])
df
I need to plot line charts of (x,y) colums with respect to the same condition. The expected result plot is:
我需要在相同条件下绘制 (x,y) 列的折线图。预期结果图是:
Of course, this image is manually given by the following code:
当然,这张图片是通过以下代码手动给出的:
pd.DataFrame([[0,.1],[1,.5]]).plot(kind="line", x=0, y=1, style="-", legend=None, title="a: 10, b: 20")
plt.xlabel("x")
plt.ylabel("y")
plt.figure()
pd.DataFrame([[0,.33],[1,.11]]).plot(kind="line", x=0, y=1, style="-", legend=None, title="a: 100, b: 200")
plt.xlabel("x")
plt.ylabel("y")
My question is how to dynamically make plots like above when getting a dataframe including condition columns, x and y.
我的问题是如何在获取包含条件列 x 和 y 的数据框时动态地绘制如上图。
Update
更新
Column names are fixed. However, values of condition columns is dynamically changed. So, I can not use the values 10, 20, 100, 200.
列名是固定的。但是,条件列的值是动态更改的。所以,我不能使用值 10、20、100、200。
Update2
更新2
If I have the below "filter_with_a_and_b" method, I think the problem solved:
如果我有下面的“filter_with_a_and_b”方法,我认为问题解决了:
def filter_with_a_and_b(df, a_b):
# how to implement?
a_b_list = df.drop_duplicates(["a","b"])
new_df_list = filter_with_a_and_b(df, a_b)
for idx, df in enumerate(new_df_list):
df.plot(title=a_b_list[idx])
回答by MaxU
is that what you want?
那是你要的吗?
df.loc[(df.a == 10) & (df.b == 20), ['x','y']].plot(title='a: 10, b: 20')
and now let's do it bit smarter:
现在让我们更聪明一点:
cond = {'a': 100, 'b': 200}
df.loc[(df.a == cond['a']) & (df.b == cond['b']), ['x','y']].plot(title='a: {a}, b: {b}'.format(**cond))
or using query()
:
或使用query()
:
q = 'a == 100 and b == 200'
df.query(q)[['x','y']].plot(title=q)
UPDATE:
更新:
a_b_list = df[['a','b']].drop_duplicates()
[df.loc[(df.a == tup[0]) & (df.b == tup[1]), ['x','y']] \
.plot(x='x', y='y', kind='line', style='-',title='a: {0[0]}, b: {0[1]}'.format(tup)) \
.set_ylabel('y')
for tup in a_b_list.itertuples(index=False)]