我的循环仅保存上一次迭代的结果

时间:2018-11-03 15:40:46

标签: python pandas

string.gsub

这是我的数据

select(2, string.gsub("\\", "\\", ""))

我创建了以下函数来清理循环,并创建一个for循环以遍历ts中的每个元素并根据1的输出进行保存。

import numpy as np
import pandas as pd

问题是我的结果ts = pd.DataFrame([0,1,2,3,4,5,6,7,8,9,10,11,12]) ts.columns = ["TS"] start_df = pd.Series([1,3,6]) end_df = pd.Series([2,7,10]) 仅保存了上一次迭代的结果check_ifdef check_if(start, ts, end): if start <= ts <= end: return 1 else: return 0 ts["Flagg"] = np.nan for ix, hour in enumerate (ts["TS"]): for jx, end in enumerate(end_df): ts["Flagg"][ix] = check_if(start_df[jx], hour, end_df[jx]) 。我的逻辑完全是出于循环吗?

修改:
预期的产量

ts["Flagg"]
start_df == 6列中

2 个答案:

答案 0 :(得分:2)

between与列表理解一起用于布尔掩码列表,然后对列表sum使用True来计数1(类似于ts['new'] = np.sum([ts['TS'].between(x, y) for x, y in zip(start_df, end_df)], axis=0) print (ts) TS new 0 0 0 1 1 1 2 2 1 3 3 1 4 4 1 5 5 1 6 6 2 7 7 2 8 8 1 9 9 1 10 10 1 11 11 0 12 12 0 的过程),感谢@RafaelC的改进:

print ([ts['TS'].between(x, y) for x, y in zip(start_df, end_df)])

[0     False
1      True
2      True
3     False
4     False
5     False
6     False
7     False
8     False
9     False
10    False
11    False
12    False
Name: TS, dtype: bool, 0     False
1     False
2     False
3      True
4      True
5      True
6      True
7      True
8     False
9     False
10    False
11    False
12    False
Name: TS, dtype: bool, 0     False
1     False
2     False
3     False
4     False
5     False
6      True
7      True
8      True
9      True
10     True
11    False
12    False
Name: TS, dtype: bool

详细信息

react-chartjs-2

答案 1 :(得分:0)

您可以创建列(系列,列表),然后将其设置为jezrael指向的列,或者创建具有一些初始值的列,然后在循环中更改它们:

ts["Flagg"] = [0 for _ in range(ts.size)]
for ix, hour in enumerate (ts["TS"]):
    for jx, end in enumerate(end_df):
        ts["Flagg"][ix] = check_if(start_df[jx], hour, end_df[jx])
相关问题