繁体   English   中英

Pandas DataFrame:根据现有列的值检查将值写入列

[英]Pandas DataFrame: Writing values to column depending on a value check of existing column

我想在pd.DataFrame中添加一列,我在其中根据现有列中的检查来写入值。

我想检查字典中的值。 假设我有以下字典:

{"<=4":[0,4], "(4,10]":[4,10], ">10":[10,inf]}

现在我想检查我的DataFrame中的一列,如果此列中的值属于字典中的任何间隔。 如果是这样,我想将匹配的字典键写入同一数据帧中的第二列。

所以DataFrame就像:

     col_1
  a    3
  b    15
  c    8

会变成:

     col_1   col_2
  a    3     "<=4"
  b    15    ">10"
  c    8     "(4,10]"

pd.cut()函数用于将连续变量转换为分类变量,在这种情况下我们有[0 , 4 , 10 , np.inf] ,这意味着我们有3个类别[0 , 4][4 , 10] [0 , 4 , 10 , np.inf] [4 , 10][10 , inf] ,因此04之间的任何值都将分配给类别[ 0 , 4]410之间的任何值都将分配给类别[ 4 , 10 ] ,依此类推。

然后你以相同的顺序为每个类别指定一个名称,你可以使用label参数来做到这一点,在这种情况下我们有3个类别[0 , 4] [4 , 10][10 , inf][10 , inf] ,只是我们将['<=4' , '(4,10]' , '>10']分配给label参数,这意味着[0 , 4]类别将被命名为<=4[4 , 10] ['<=4' , '(4,10]' , '>10'] [4 , 10]类别将命名为(4,10] ,依此类推。

In [83]:
df['col_2'] = pd.cut(df.col_1 , [0 , 4 , 10 , np.inf] , labels = ['<=4' , '(4,10]' , '>10'] )
df
Out[83]:
   col_1    col_2
0   3       <=4
1   15      >10
2   8       (4,10]

你可以使用这种方法:

dico = pd.DataFrame({"<=4":[0,4], "(4,10]":[4,10], ">10":[10,float('inf')]}).transpose()

foo = lambda x: dico.index[(dico[1]>x) & (dico[0]<=x)][0]

df['col_1'].map(foo)

#0       <=4
#1       >10
#2    (4,10]
#Name: col1, dtype: object

此解决方案创建一个名为extract_str的函数,该函数应用于col_1 它使用条件列表推导来遍历字典中的键和值,检查值是否大于或等于较低值且小于较高值。 进行检查以确保此结果列表不包含多个结果。 如果列表中有值,则返回该值。 否则默认返回None

from numpy import inf

d = {"<=4": [0, 4], "(4,10]": [4, 10], ">10": [10, inf]}

def extract_str(val):
    results = [key for key, value_range in d.iteritems() 
               if value_range[0] <= val < value_range[1]]
    if len(results) > 1:
        raise ValueError('Multiple ranges satisfied.')
    if results:
        return results[0]

df['col_2'] = df.col_1.apply(extract_str)

>>> df
   col_1   col_2
a      3     <=4
b     15     >10
c      8  (4,10]

在这个小型数据框架上,此解决方案比@ColonelBeauvel提供的解决方案快得多。

%timeit df['col_2'] = df.col_1.apply(extract_str)
1000 loops, best of 3: 220 µs per loop

%timeit df['col_2'] = df['col_1'].map(foo)
1000 loops, best of 3: 1.46 ms per loop

您可以使用函数进行映射。 像例子。 我希望它可以帮助你。

import pandas as pd
d = {'col_1':[3,15,8]}
from numpy import inf
test = pd.DataFrame(d,index=['a','b','c'])
newdict = {"<=4":[0,4], "(4,10]":[4,10], ">10":[10,inf]}

def mapDict(num):
    print(num)
    for key,value in newdict.items():
        tmp0 = value[0]
        tmp1 = value[1]
        if num == 0:
            return "<=4"
        elif (num> tmp0) & (num<=tmp1):
            return key

test['col_2']=test.col_1.map(mapDict)

然后测试将成为:

  col_1 col_2
a   3   <=4
b   15  >10
c   8   (4,10]

PS。 我想知道如何快速编写堆栈溢出代码,是否有人可以告诉我这些技巧?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM