【发布时间】:2021-09-27 11:11:44
【问题描述】:
我想知道 Python 中是否有一种“when 语句”。例如,在下面的代码中,在某些时候所有观察结果都是正确的。我写它的方式,只读取第一个语句而忽略其他 2。我怎样才能使它在特定条件下打印所有观察的计数?
counts_zero_time = 0
counts_zero_time_non_zero_dist = 0
counts_zero_time_zero_dist = 0
for index,row in df.iterrows():
if row["time_interval"] == 0:
counts_zero_time += 1
elif row["time_interval"] == 0 and row["distance"] !=0:
counts_zero_time_non_zero_dist += 1
elif row["time_interval"] == 0 and row["distance"] ==0:
counts_zero_time_zero_dist += 1
print(counts_zero_time, "observations have a time interval of 0")
print(counts_zero_time_non_zero_dist, "observations have a time interval of 0 and a non-zero distance")
print(counts_zero_time_zero_dist, "observations have a time interval and distance of 0")
在输出中,我得到第一个条件的正确计数,但其他两个不正确的计数为零。
1421 observations have a time interval of 0
0 observations have a time interval of 0 and a non-zero distance
0 observations have a time interval and distance of 0
【问题讨论】:
-
您可以将
elif替换为if。但更好的方法是使用 pandas 表达式。那么你不需要遍历数据框 -
您的意思是添加单独的行来打印计数吗?像这样 zero_interval =
trip_char.loc[(df["time_interval"] == 0)]然后打印它的长度? -
是的,类似的。请看我的回答
标签: python for-loop if-statement count conditional-statements