【发布时间】:2020-11-20 05:47:47
【问题描述】:
我的函数中有一个 if else 语句没有按照我想要的方式工作。请注意,我仍在学习 python 和所有编程。
我有一个函数来定义一个情节。想法是创建一个用于数据分析的大型 python 存储库。编辑:我添加了一个工作轮班数据框供您尝试
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'])
这里的想法是,如果 cond 值中没有数据,请执行pass 以不显示绘图。
但是每次我运行它时,情节都会显示,甚至认为没有数据。
当我调用我放入plot_timeseries(time=time_data, depth=depth_data temp=temp_data)的函数时
我的目标是仅显示此示例中的临时数据,而不是没有变量的条件图。
我试过的是
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().
【问题讨论】:
-
我无法重现这个。你能创建一个minimal reproducible example吗?
-
@DavidG,我现在将编辑原帖
-
谢谢。
cond是熊猫系列。所以你可以使用if cond.empty: -
我试过这个并给了我一个属性错误。我不认为 python 知道这些变量是 panda df,也许,因为在我的 repo 中我从另一个 python 文件中获取它们。
标签: python-3.x matplotlib if-statement plot time-series