【问题标题】:Split pandas dataframe conditionally to plot with different colors有条件地拆分熊猫数据框以绘制不同的颜色
【发布时间】:2018-03-05 00:34:10
【问题描述】:

我有带有一对值的 pandas 数据框,并且喜欢有条件地对其进行颜色编码,例如

df.plot(kind='scatter', ax=ax1, x='a', y='b', c=np.where(['a']>0.5, 'r', 'g']))

但没有到达任何地方。对ab 应用相同的条件是最终目标。任何线索都值得赞赏。

【问题讨论】:

    标签: python pandas numpy matplotlib


    【解决方案1】:

    演示:

    In [50]: df = pd.DataFrame(np.random.rand(100, 2), columns=['x','y'])
    
    In [51]: df.head()
    Out[51]:
              x         y
    0  0.376715  0.209387
    1  0.633065  0.212350
    2  0.538783  0.883493
    3  0.753707  0.983746
    4  0.135703  0.840134    
    
    In [52]: df.plot.scatter(x='x', y='y', s=20, c=np.where(df['y']>0.5, 'r', 'g'))
    Out[52]: <matplotlib.axes._subplots.AxesSubplot at 0x1078f4e0>
    

    更新:

    是否可以在其中嵌套两个条件,例如 c=np.where(df_AA['a']&gt;0.5 and df_AA['b']&lt;0.5, 'r', 'b')

    In [70]: df.plot.scatter(x='x', y='y', s=20, c=np.where((df['x']>0.5) & (df['y']<0.5), 'r', 'g'), grid=True)
    Out[70]: <matplotlib.axes._subplots.AxesSubplot at 0xc166dd8>
    

    【讨论】:

    • 是否可以在其中嵌套两个条件,例如c=np.where(df['a']&gt;0.5 and df['b']&lt;0.5, 'r', 'b')
    • 最后一件事,我们可以把网格分成 4 个象限吗?
    • 我认为嵌套np.where 会很容易,但事实证明这很困难。我也想在同一个情节上红色值(df['x']&lt;0.5) &amp; (df['y']&gt;0.5)。将其与另一个 &amp; 包括在内会引发错误
    • @Ibe,你到底想做什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2019-12-14
    • 1970-01-01
    • 2018-04-26
    相关资源
    最近更新 更多