簡體   English   中英

Python:有條件地在循環中從 Dataframe 的多列中繪制數據

[英]Python: Conditionally plotting data from many columns from a Dataframe in a loop

我在 dataframe 中有大約 200 對列,我想在單個 plot 中使用 plot。 每對列都可以被認為是相關的“x”和“y”變量。 某些“y 變量”在數據中的某些點為 0。 我不想 plot 那些。 我寧願它們在 plot 中顯示為不連續性。 我無法找出排除這些變量的有效方法。 plot 中還有一個我不需要的“日期”變量,但我將其保留在示例數據中只是為了反映現實。

這是一個示例數據集以及我用它做了什么。 我匆忙創建了我的示例數據集,原始數據對於每對列數據的給定“x 值”具有唯一的“y 值”。

import pandas as pd
from numpy.random import randint

data1y = [n**3 -n**2+n for n in range(12)]
data1x = [randint(0, 100) for n in range(12)]
data1x.sort()
data2y = [n**3 for n in range(12)]
data2x = [randint(0, 100) for n in range(12)]
data2x.sort()
data3y = [n**3 - n**2 for n in range(12)]
data3x = [randint(0, 100) for n in range(12)]
data3x.sort()
data1y = [0 if x%7==0 else x for x in data1y]
data2y = [0 if x%7==0 else x for x in data2y]
data3y = [0 if x%7==0 else x for x in data3y]

date = ['Jan','Feb','Mar','Apr','May', 'Jun','Jul','Aug','Sep','Oct','Nov','Dec']
df = pd.DataFrame({'Date':date,'Var1':data1y, 'Var1x':data1x, 'Vartwo':data2y, 'Vartwox':data2x,'datatree':data3y, 'datatreex':data3x})

print(df)

ax = plt.gca()
fig = plt.figure()
for k in ['Var1','Vartwo','datatree']:
    df.plot(x=k+'x', y=k, kind = 'line',ax=ax)enter code here

output 我得到這個: 在此處輸入圖像描述

我希望看到“y 變量”為零的不連續性。

我努力了:

import numpy as np
df2 = df.copy()
df2[df2.Var1 < 0.5] = np.nan

但是當我只希望它是一個特定的變量時,這會產生一整行 NaN。

在此處輸入圖像描述

我正在嘗試這個,但它不起作用。

ax = plt.gca()
fig = plt.figure()
for k in ['Var1','Vartwo','datatree']:
    filter = df.k.values > 0
    x = df.k+'x'
    y = df.k
    plot(x[filter], y[filter], kind = 'line',ax=ax)

這適用於單個變量,但我不知道如何在 200 個變量中循環它,這也沒有顯示不連續性。

import matplotlib.pyplot as plt
ax = plt.gca()
fig = plt.figure()
for k in ['Var1','Vartwo','datatree']:
    filter = df.Var1.values > 0
    x = df.Var1x[filter]
    y = df.Var1[filter]
    plt.plot(x, y)

您正在尋找.replace()

df2 = df.copy()
cols_to_replace = ['Var1','Var1x','Vartwo']
df2[cols_to_replace] = df2[cols_to_replace].replace({0:np.nan})

fig, ax = plt.subplots()
for k in ['Var1','Vartwo','datatree']:
    df2.plot(x=k+'x', y=k, kind = 'line',ax=ax)

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM