簡體   English   中英

根據另一列中的值將列添加到Python pandas DataFrame

[英]Add column to a Python pandas DataFrame based on values in an other column

我想根據其他列之一中的值向pandas DataFrame添加一列。

import pandas as pd
import numpy as np

Records = 100

df = pd.DataFrame (
        {'ID' : range(1, Records + 1),
         'Group' : np.random.choice(range(1, 41), Records, replace = True)
         }
        )

def Age(x):
    a = list()
    for i in x:
        if (i >= 14 and i <= 20) or (i >= 34 and i <= 40):
            a.append('65+')
        else:
            a.append('65-')
    return a

df['Age'] = Age(df.Group)

print(df.head(10))

    Group  ID  Age
0      11   1  65-
1       1   2  65-
2       6   3  65-
3      32   4  65-
4      31   5  65-
5      39   6  65+
6      26   7  65-
7      38   8  65+
8      26   9  65-
9      31  10  65-

這樣就可以了,但是我更喜歡使用lambda函數,但是不能正常工作。 或者,如果可能,在創建數據框時創建“年齡”列。 有什么建議么?

使用numpy.where是非常快速的矢量化函數:

m = ((df['Group'] >= 14) & (df['Group'] <= 20)) | ((df['Group'] >= 34) & (df['Group'] <= 40))
df['new'] = np.where(m, '65+','65-')
print (df)
   Group  ID  Age  new
0     11   1  65-  65-
1      1   2  65-  65-
2      6   3  65-  65-
3     32   4  65-  65-
4     31   5  65-  65-
5     39   6  65+  65+
6     26   7  65-  65-
7     38   8  65+  65+
8     26   9  65-  65-
9     31  10  65-  65-

時間

Records = 1000000

In [94]: %timeit df['Age1'] = np.where((df['Group'] >= 14) & (df['Group'] <= 20) | (df['Group'] >= 34) & (df['Group'] <= 40), '65+','65-')
10 loops, best of 3: 123 ms per loop

In [95]: %timeit df['Age2'] = df['Group'].apply(lambda x: '65+' if ((x >= 14 and x <= 20) or (x >= 34 and x <= 40)) else '65-')
1 loop, best of 3: 253 ms per loop

選項1
重新考慮條件。
請注意,兩個間隔均為寬度6
請注意,間隔之間的中點是27

cats = np.array(['65-', '65+'])
cond = df.Group.sub(27).abs().pipe(lambda x: x.ge(7) & x.le(13)).astype(int)
df.assign(Age=cats[cond])

   Group  ID  Age
0     11   1  65-
1      1   2  65-
2      6   3  65-
3     32   4  65-
4     31   5  65-
5     39   6  65+
6     26   7  65-
7     38   8  65+
8     26   9  65-
9     31  10  65-

我們可以通過使用底層數組來加快速度

cats = np.array(['65-', '65+'])
arr1 = np.abs(df.Group.values - 27)
cond = ((arr1 >= 7) & (arr1 <= 13)).astype(int)
df.assign(Age=cats[cond])

   Group  ID  Age
0     11   1  65-
1      1   2  65-
2      6   3  65-
3     32   4  65-
4     31   5  65-
5     39   6  65+
6     26   7  65-
7     38   8  65+
8     26   9  65-
9     31  10  65-

選項2
使用np.searchsorted
使用[13, 20, 33, 40]的整數斷點。 searchsorted會告訴我們每個Group值在哪里,然后我們對標簽數組進行切片以提供所需的內容。

b = np.array([13, 20, 33, 40])
c = np.array(['65-', '65+', '65-', '65+', '65-'])
df.assign(Age=c[np.searchsorted(b, df.Group.values)])

   Group  ID  Age
0     11   1  65-
1      1   2  65-
2      6   3  65-
3     32   4  65-
4     31   5  65-
5     39   6  65+
6     26   7  65-
7     38   8  65+
8     26   9  65-
9     31  10  65-

與適用於df.Group系列

Records = 100

df = pd.DataFrame (
        {'ID' : range(1, Records + 1),
         'Group' : np.random.choice(range(1, 41), Records, replace = True)
         }
        )

#Here is the apply:
df['Age'] = df['Group'].apply(lambda x: '65+' if ((x >= 14 and x <= 20) or
                                                  (x >= 34 and x <= 40)) else '65-')
print(df.head())

結果:

    Group ID  Age
0      3   1  65-
1     25   2  65-
2      6   3  65-
3     23   4  65-
4     20   5  65+
...

暫無
暫無

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

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