简体   繁体   English

对于列中的每个唯一元素,创建一个具有其对应特征的图形

[英]For each unique element in a column, create a plot with it's corresponding features

I believe that my problem is really straightforward and there must be a really easy way to solve this issue with pandas that I am still not aware of. 我认为我的问题确实很简单,必须有一种非常简单的方法来解决我仍然不知道的熊猫问题。 I don't really want to create new dataframes. 我真的不想创建新的数据框。 I have already spent some time trying to figure out by myself but could not reach a result. 我已经花了一些时间试图自己弄清楚,但无法取得结果。

A simple example might be a better way to explain my goal: I have four different unique values, indicated by the code below, on the column C. What I want is to create a for loop where for each of this unique values (Value_1, Value_2, Value_3, Value_4), plot a graph which the 'x' is the corresponding feature in Column A for that value and 'y' is the corresponding column B. 一个简单的示例可能是解释我的目标的更好方法:在C列上有四个不同的唯一值,如下面的代码所示。我想要的是创建一个for循环,其中每个唯一值(Value_1, Value_2,Value_3,Value_4),绘制一个图形,其中“ x”是该值在列A中的对应特征,而“ y”是对应的列B。

import pandas as pd
data = {'Column A': [100,200,300,400,500,500,500,300],
    'Column B': [1,1,2,2,3,3,0,2], 
    'Column C': ["Value_1", "Value_2", "Value_3", "Value_4", "Value_1", "Value_2", "Value_3", "Value_4"]}
df = pd.DataFrame(data, columns=['Column A','Column B', 'Column C'])

I would expect afterwards a result, as for this case where I would receive four plots, where each represents one of the values of the column C and the correspondings features of column A and B. 对于这种情况,我希望得到一个结果,因为在这种情况下,我将收到四个图,每个图代表C列的值之一以及A和B列的对应特征。

I have tried the following: 我尝试了以下方法:

for d in df.groupby(df['Column C']):
df.plot.scatter(x='Column A', y='Column B', marker='.')
plt.show()

However by doing so, I am not able to really achieve what I want as all the points are plotted in this graph, without the filtering that I want to implement with column C. 但是,这样做时,由于没有在C列中实现的过滤功能,因此我无法真正实现所需的功能,因为此图中绘制了所有点。

Hope that I could succinct and precise. 希望我能简洁明了。 Wish you the best and thanks for the attention. 祝您一切顺利,并感谢您的关注。

I guess you can just loop over the unique values with this: 我想您可以使用以下方法遍历唯一值:

for val in df['Column C'].unique():
    sdf = df.loc[df['Column C']==val]
    sdf.plot(x='Column A', y='Column B', label='C = {}'.format(val))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM