【发布时间】:2020-02-10 16:14:06
【问题描述】:
我尝试遍历我的数据并检查一列(雨)是否大于 0,如果为真,我需要在 i 索引之前取 100 行,如果 i 小于 100,我忽略它并继续运行,并将它们添加到另一个数据框中。 我的代码:
import pandas as pd
data = pd.read_csv('weather_forecast.csv')
data_before_rain = pd.DataFrame()
for index,row in data.iterrows():
if row['rain'] > 1:
data_before_rain.append(data.iloc[(index-100):index])
print(data_before_rain)
DataFrame 数据示例:
time ghi dni ... barometric_pressure rain sensor_cleaning
0 01/07/2018 07:14 34 0 ... 981.8 0.1 0
1 01/07/2018 07:15 34 0 ... 981.9 0.0 0
2 01/07/2018 07:16 35 0 ... 981.9 0.0 0
3 01/07/2018 07:17 36 0 ... 981.9 0.0 0
4 01/07/2018 07:18 37 0 ... 981.9 0.1 0
5 01/07/2018 07:19 38 0 ... 982.0 0.0 0
6 01/07/2018 07:20 39 0 ... 982.0 0.0 0
7 01/07/2018 07:21 40 0 ... 982.0 0.0 0
8 01/07/2018 07:22 42 0 ... 982.0 0.0 0
9 01/07/2018 07:23 43 0 ... 982.0 0.0 0
10 01/07/2018 07:24 44 0 ... 982.0 0.0 0
11 01/07/2018 07:25 45 0 ... 982.0 0.1 0
12 01/07/2018 07:26 46 0 ... 982.1 0.0 0
当我尝试使用 = (data_before_rain = data.iloc[index-100:index]) 代替 append() 方法时,它仅适用于最后 100 行。
当我尝试append() 方法时,输出是:
Empty DataFrame
Columns: []
Index: []
我该怎么做?
【问题讨论】:
-
检查
for i in data:实际在做什么(试试for i in data: print(i))。 (提示,数据帧有自己的迭代方法,df.iterrows()) -
@Ram Rahamim if
rain > 1then get last 100 rows and put to the new df, if there are no 100 rows beforerain > 1pass and continue search? -
@ZarakiKenpachi 是的。
标签: python pandas dataframe for-loop if-statement