簡體   English   中英

(Pandas)組合兩個數據幀的不同方式

[英](Pandas) Different way of combining two dataframes

如果有更好的方法來組合兩個數據幀而不是我在下面做的話,那我就是在徘徊。

import pandas as pd

#create ramdom data sets
N = 50
df = pd.DataFrame({'date': pd.date_range('2000-1-1', periods=N, freq='H'),
 'value': np.random.random(N)})

index = pd.DatetimeIndex(df['date'])
peak_time = df.iloc[index.indexer_between_time('7:00','9:00')]
lunch_time = df.iloc[index.indexer_between_time('12:00','14:00')]

comb_data = pd.concat([peak_time, lunch_time], ignore_index=True)

有沒有辦法在使用邏輯運算符的between_time時組合兩個范圍?

我必須使用它在df中創建一個名為'isPeak'的新列,其中當它在7:00~9:00和12:00~14:00之間的范圍內寫入1時,如果沒有則為0。

對我來說工作np.union1d

import numpy as np

idx = np.union1d(index.indexer_between_time('7:00','9:00'), 
                 index.indexer_between_time('12:00','14:00'))

comb_data = df.iloc[idx]
print (comb_data)
                  date     value
7  2000-01-01 07:00:00  0.760627
8  2000-01-01 08:00:00  0.236474
9  2000-01-01 09:00:00  0.626146
12 2000-01-01 12:00:00  0.625335
13 2000-01-01 13:00:00  0.793105
14 2000-01-01 14:00:00  0.706873
31 2000-01-02 07:00:00  0.113688
32 2000-01-02 08:00:00  0.035565
33 2000-01-02 09:00:00  0.230603
36 2000-01-02 12:00:00  0.423155
37 2000-01-02 13:00:00  0.947584
38 2000-01-02 14:00:00  0.226181

替代numpy.r_

idx = np.r_[index.indexer_between_time('7:00','9:00'), 
            index.indexer_between_time('12:00','14:00')]

comb_data = df.iloc[idx]
print (comb_data)
                  date     value
7  2000-01-01 07:00:00  0.760627
8  2000-01-01 08:00:00  0.236474
9  2000-01-01 09:00:00  0.626146
31 2000-01-02 07:00:00  0.113688
32 2000-01-02 08:00:00  0.035565
33 2000-01-02 09:00:00  0.230603
12 2000-01-01 12:00:00  0.625335
13 2000-01-01 13:00:00  0.793105
14 2000-01-01 14:00:00  0.706873
36 2000-01-02 12:00:00  0.423155
37 2000-01-02 13:00:00  0.947584
38 2000-01-02 14:00:00  0.226181

使用Index.union純pandas解決方案並將數組轉換為index

idx = (pd.Index(index.indexer_between_time('7:00','9:00'))
         .union(pd.Index(index.indexer_between_time('12:00','14:00'))))

comb_data = df.iloc[idx]
print (comb_data)
                  date     value
7  2000-01-01 07:00:00  0.760627
8  2000-01-01 08:00:00  0.236474
9  2000-01-01 09:00:00  0.626146
12 2000-01-01 12:00:00  0.625335
13 2000-01-01 13:00:00  0.793105
14 2000-01-01 14:00:00  0.706873
31 2000-01-02 07:00:00  0.113688
32 2000-01-02 08:00:00  0.035565
33 2000-01-02 09:00:00  0.230603
36 2000-01-02 12:00:00  0.423155
37 2000-01-02 13:00:00  0.947584
38 2000-01-02 14:00:00  0.226181

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM