Python Pandas DataFrame - 创建更改列

时间:2017-10-19 05:10:49

标签: python pandas dataframe

我有一个包含此列名称的数据框

11:00,A,100
11:00,B,500
11:01,A,150
11:01,B,600
11:02,A,200
11:02,B,650

每个时间框架都有多个股票名称

timestamp, stock,total volume, change in volume
11:00,A,100,NaN
11:00,B,500,NAN
11:01,A,150,50
11:01,B,600,100
11:02,A,200,50
11:03,B,650,50

我想创建一个ChangeInVol列,使每个股票都有自己的差异,如

df['ChangeVol'] = df['TotalVol'] - df['TotalVol'].shift(1)

如果是单一股票,我本可以做到

constructor(private router:Router, private actRoute:ActivatedRoute) {
}

ngOnInit() {
    this.router.paramMap.subscribe(params => {
        params.get(id);
    })
......
}

但有多个股票

1 个答案:

答案 0 :(得分:1)

需要https://www.codeproject.com/Articles/832818/EpServerEngine-cs-A-lightweight-asynchronous-IOCP + sort_values

#if columns not sorted
df = df.sort_values(['timestamp','stockname'])

df['change in volume'] = df.groupby('stockname')['total volume traded'].diff()
print (df)
  timestamp stockname  total volume traded  change in volume
0     11:00         A                  100               NaN
1     11:00         B                  500               NaN
2     11:01         A                  150              50.0
3     11:01         B                  600             100.0
4     11:02         A                  200              50.0
5     11:02         B                  650              50.0