熊猫从指定的行号迭代通过行

问题描述:

我想通过从特定行号开始遍历行读取熊猫数据框中的数据。我知道有df.iterrows(),但它不让我指定从哪里开始迭代。熊猫从指定的行号迭代通过行

在我的特定情况下,我有可能会是这个样子的CSV文件:

Date, Temperature 
21/08/2017 17:00:00,5.53 
21/08/2017 18:00:00,5.58 
21/08/2017 19:00:00,4.80 
21/08/2017 20:00:00,4.59 
21/08/2017 21:00:00,3.72 
21/08/2017 22:00:00,3.95 
21/08/2017 23:00:00,3.11 
22/08/2017 00:00:00,3.07 
22/08/2017 01:00:00,2.80 
22/08/2017 02:00:00,2.75 
22/08/2017 03:00:00,2.79 
22/08/2017 04:00:00,2.76 
22/08/2017 05:00:00,2.76 
22/08/2017 06:00:00,3.06 
22/08/2017 07:00:00,3.88 

我想遍历每个行从一个特定的时间点上(让我们说8月22日的午夜) ,所以我想实现这样的:

df = pandas.read_csv('file.csv') 
start_date = '22/08/2017 00:00:00' 

// since it's sorted, I figured I could use binary search 
result = pandas.Series(df['Date']).searchsorted(start_date) 

result[0]居然给了我正确的号码。

我想我可以做的只是增加这个数字,并通过df.iloc[[x]]访问该行,但我觉得这样做很脏。

for x in range(result[0], len(df)): 
    row = df.loc[[x]] 

我到目前为止发现的所有答案只显示如何遍历整个表。

只是过滤您的数据帧调用iterrows()前:

df['Date'] = pandas.to_datetime(df['Date']) 
for idx, row in df[df['Date'] >= '2017-08-22'].iterrows(): 
    # 
    # Whatever you want to do in the loop goes here 
    # 

请注意,这是没有必要的过滤参数转换'2017-08-22'到一个datetime的对象,因为熊猫可以处理partial string indexing

+0

+1,因为即使我查找的确切日期时间不在表格中,它也能正常工作。只是提醒一下,它会按字母顺序比较字符串 - 如果转换为日期时间,则工作正常。 –

+0

我假设你在谈论'Date'这个列是datetime对象,而不是一个字符串。你是对的,我是假设的。我会更新帖子。 – kev8484

+0

应该更具体一点。谢谢你的帮助 –

Date转换为datetime。设置Dateindex

df.Date = pd.to_datetime(df.Date) 

df = df.set_index('Date') 

然后:

for date, row in df['22/08/2017 00:00:00':].iterrows(): 
    print(date.strftime('%c'), row.squeeze()) 

Tue Aug 22 00:00:00 2017 3.07 
Tue Aug 22 01:00:00 2017 2.8 
Tue Aug 22 02:00:00 2017 2.75 
Tue Aug 22 03:00:00 2017 2.79 
Tue Aug 22 04:00:00 2017 2.76 
Tue Aug 22 05:00:00 2017 2.76 
Tue Aug 22 06:00:00 2017 3.06 
Tue Aug 22 07:00:00 2017 3.88 
+0

哦,整齐。没想到只是把桌子切成片。 –