if-else语句python使用函数中的plot参数



我的函数中有一个if-else语句,它没有按照我想要的方式运行。请注意,我仍在学习python和所有编程。

我有一个函数来定义一个绘图。想法是创建一个用于数据分析的大型python repo。编辑:我添加了一个正在工作的临时数据帧,供您尝试

import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
#import numpy as np
#import os
#import dir_config as dcfg
#import data_config as datacfg
import matplotlib.dates as md
#import cartopy.crs as ccrs
data = {'dates': [20200901,20200902,20200903,20200904,20200905,20200906,20200907,20200908,20200909,20200910],
'depth': [1,2,3,4,5,6,7,8,9,10],
'cond': [30.1,30.2,30.3,30.6,31,31.1,31.0,31.4,31.1,30.9]
}
df = pd.DataFrame(data, columns = ['dates', 'depth', 'cond'])
df['pd_datetime'] = pd.to_datetime(df['dates'])

def ctd_plots_timeseries(time=[],cond=[], sal =[], temp=[], depth=[], density=[]):
#-----------
# CONDUCTIVITY PLOT
#-----------

if cond == []:
print("there is no data for cond")
pass
else:
plt.scatter(time,depth,s=15,c=cond,marker='o', edgecolor='none')
plt.show()
#-----------
# SALINITY (PSU) PLOT: I do not want this to plot at all due to its parameter being 'empty' in the function when called
#-----------
if sal == []:
print('there is no salinity data')
pass
else:
plt.scatter(time,depth,s=15,c=sal,marker='o', edgecolor='none')
plt.show()

ctd_plots_timeseries(depth = df['depth'], time = df['pd_datetime'], cond = df['cond'])

这里的想法是,如果第二个值中没有数据,则执行pass以不显示绘图。然而,每当我运行这个,情节显示,甚至认为没有数据。

当我调用我放入plot_timeseries(time=time_data, depth=depth_data temp=temp_data)中的函数时

我的目的是只显示这个例子中的临时数据,而不是一个没有变量的cond图。

我试过的是

if cond != []:
plotting code
plt.show()
else:
print('there is no cond data')
pass

plotting code
if cond == []:
print('no cond data')
pass
else:
plt.show()

但无济于事。

注意,在这个函数中还有4个其他的图,我想做同样的事情。感谢这个社区能给我的任何见解。

更新:我将函数中的条件更改为def ctd_plots_timeseries(time=0,cond=0, sal =0, temp=0, depth=0, density=0):然后将条件语句更改为

if cond != 0:
graphing code
else:
print('no data here')

我得到以下错误:ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我已经简化了它。试试看:

def plots_timeseries(cond = []): # Single argument for clarity
if not cond:
print('there is no cond value')
else:
print('There is cond')
plots_timeseries()
# there is no cond value

所以我找到了一个可行的解决方案。

if len(cond) == 0:
print('there is no cond data')
else:
plt.scatter(time,depth,s=15,c=cond)
plt.show()

我们花了很多时间和精力试图解决这个问题,这个解决方案是一个测试,在睡了一个好觉之后。谢谢你的帮助。希望这能帮助其他人,如果他们有类似的问题

最新更新