[英]Using a function to create a data-frame column
我有一個名為df
的 dataframe 看起來像:
dept ratio higher lower
date
01/01/1979 B 0.522576565 2 1
01/01/1979 A 0.940614079 2 2
01/01/1979 C 0.873957946 0 1
01/01/1979 B 0.087828824 0 2
01/01/1979 A 0.39754345 1 2
01/01/1979 A 0.475491609 1 2
01/01/1979 B 0.140605283 0 2
01/01/1979 A 0.071007362 0 2
01/01/1979 B 0.480720923 2 2
01/01/1979 A 0.673142643 1 2
01/01/1979 C 0.73554271 0 0
我想創建一個名為 compare 的新列,其中對於每一行我想計算dept
列中compared
行dept
值減去 1 匹配的值的數量。如果計數大於或等於 1,那么我想返回到compared
列的解決方案如下:
`compared` row value = (higher - lower) / count of dept column which matches the dept row value - 1
如果部門數為 0,則比較列將返回 0。
例如,對於df
中的第一行, dept
值為 B。在dept
列中有 4 個 B 值。 4-1 大於 1。因此,在新compared
的列中,我想輸入higher
的列值 (2) 減去lower
的列值 (1),等於 1 除以 4-1
或者
(2-1)/(4-1) = 0.333333333
所以我想要的 output 看起來像:
dept ratio higher lower compared
date
01/01/1979 B 0.522576565 2 1 0.333333333
01/01/1979 A 0.940614079 2 2 0.000000000
01/01/1979 C 0.873957946 0 1 -1.000000000
01/01/1979 B 0.087828824 0 2 -0.666666667
01/01/1979 A 0.39754345 1 2 -0.250000000
01/01/1979 A 0.475491609 1 2 -0.250000000
01/01/1979 B 0.140605283 0 2 -0.666666667
01/01/1979 A 0.071007362 0 2 -0.500000000
01/01/1979 B 0.480720923 2 2 0.000000000
01/01/1979 A 0.673142643 1 2 -0.250000000
01/01/1979 C 0.73554271 0 0 0.000000000
我有一些代碼,但它真的很慢:
minDept=1
for staticidx, row in df.iterrows():
dept = row['dept']
deptCount = deptPivot.loc[dept, "date"] # if error then zero
myLongs= df.loc[staticidx, "higher"]
myShorts= df.loc[staticidx, "lower"]
if deptCount > minDept:
df.loc[staticidx, "compared"] = (higher- lower)/(deptCount-1)
else:
df.loc[staticidx, "compared"] = 0
有沒有更快的方法可以做到這一點?
這很簡單:
counts = df.groupby('dept')['dept'].transform('count')-1
df['compared'] = (df['higher']-df['lower'])/counts
# to avoid possible division by zero warning
# also to match `counts>0` condition
# use this instead
# df.loc[counts>0,'compared'] = df['higher'].sub(df['lower']).loc[counts>0]/counts[counts>0]
Output:
dept ratio higher lower compared
date
01/01/1979 B 0.522577 2 1 0.333333
01/01/1979 A 0.940614 2 2 0.000000
01/01/1979 C 0.873958 0 1 -1.000000
01/01/1979 B 0.087829 0 2 -0.666667
01/01/1979 A 0.397543 1 2 -0.250000
01/01/1979 A 0.475492 1 2 -0.250000
01/01/1979 B 0.140605 0 2 -0.666667
01/01/1979 A 0.071007 0 2 -0.500000
01/01/1979 B 0.480721 2 2 0.000000
01/01/1979 A 0.673143 1 2 -0.250000
01/01/1979 C 0.735543 0 0 0.000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.