熊猫的矩阵到小时系列

时间:2019-06-19 06:45:45

标签: python pandas datetime

我想将每小时Pandas Series转换为DataFrame,将DataFrame转换为YEAR = 2017 serie = pd.Series(pd.date_range( start=f'{YEAR}-01-01', end=f'{YEAR}-12-31 23:00:00', freq='H')) ,仅将日期和小时作为索引。

例如,假设我有这个系列:

                             h01      h02      h03     h04     h05  ...
Date
2017-01-01                   data    data     data     data   data  ...

但是我想要这样:

package pck.pramod.geekforgeeks;

public class ThreadDeadlock {

    public static Object Lock1 = new Object();
    public static Object Lock2 = new Object();

    public static void main(String args[]) {
        System.out.println(Lock1.toString() + " " + Lock2.toString());
        ThreadDemo1 T1 = new ThreadDemo1(Lock1, Lock2, "T1");
        ThreadDemo1 T2 = new ThreadDemo1(Lock2, Lock1, "T2");
        T1.start();
        T2.start();
    }

}

class ThreadDemo1 extends Thread {
    Object lock1;
    Object lock2;
    String name;

    public ThreadDemo1(Object lock1, Object lock2, String name) {
        this.lock1 = lock1;
        this.lock2 = lock2;
        this.name = name;
    }

    public void run() {
        synchronized (lock1) {
            System.out.println(name + " Holding lock ..." + lock1.toString());

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
            System.out.println(name + " Waiting for lock ..." + lock2.toString());

            synchronized (lock2) {
                System.out.println(name + " Holding lock ..." + lock1.toString() + " " + lock2.toString());
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

我相信您的SeriesDatetimeIndex在一起,并且填写了一些数据。

然后,DataFrame.pivotDataFrame.assign需要DatetimeIndex.dateDatetimeIndex.strftime创建的新列,Series.to_frame需要DataFrame的一列:

YEAR = 2017
serie = pd.Series(np.arange(8760), pd.date_range(
        start=f'{YEAR}-01-01', end=f'{YEAR}-12-31 23:00:00', freq='H'))

df = serie.to_frame('vals').assign(date = lambda x: x.index.date,
                                   hour = lambda x: x.index.strftime('h%H'))
#print (df)


df1 = df.pivot('date','hour','vals')
#print (df1)

另一种解决方案:

serie.index = [serie.index.date, serie.index.strftime('h%H')]
df1 = serie.unstack()