Python 我的循环只保存上次迭代的结果
这是我的数据:Python 我的循环只保存上次迭代的结果,python,pandas,Python,Pandas,这是我的数据: import numpy as np import pandas as pd 我创建了以下函数来清理我的循环,并创建了一个for循环来迭代ts中的每个元素,并根据check\u if的输出进行保存 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]) 在列ts[“Flagg”
import numpy as np
import pandas as pd
我创建了以下函数来清理我的循环,并创建了一个for循环来迭代ts中的每个元素,并根据check\u if
的输出进行保存
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])
在列ts[“Flagg”]
中 与列表理解一起使用布尔掩码列表,然后将其与计数True
值一起使用(1
),感谢@RafaelC的改进:
[0,1,1,1,1,2,2,1,1,1,0,0]
详细信息:
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
您可以创建列(系列、列表),然后将其设置为jezrael指向的列,或者使用一些初始值创建列,然后在循环中更改它们:
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
什么是预期输出?添加了预期输出。这非常有效!这也可以用于日期吗?请详细说明解决方案好吗?
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
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])