如何从另一个列中的熊猫中创建一个列,与列表匹配

时间:2020-04-13 21:41:44

标签: python pandas numpy

我在pandas中有一个DataFrame,其中一列有一堆位置编号。 例如:

    location
 1. 33
 2. 223
 3. 66

所以我想做的是创建另一列,将这些数字转换为列表中的区域数字。 例如:

list = [[33, 428], [223, 691], [521, 53], [83, 96], [423, 614], [360, 311], [55, 66]]

regionNumber = [1, 2, 3, 4, 5, 6, 7]

所以结果应该是

location region
33       1 
223      2
66       7

所以我尝试的方法是

        def regionid():
            i = 0
            for row in list:
                for item in row:
                    if dataframe["location"] == item:
                        return regionNumber[i]
                i = i + 1

        dataframe['Region'] = dataframe.apply(regionid(), axis=1)

我不断 ” f“ {type(self)。名称}的真值不明确。” ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。 ” 我不确定该怎么办。

2 个答案:

答案 0 :(得分:1)

创建一个dictionary并在map中使用它:

"last_visit_time":"1793021894"

输出

df['Severity'] = ""
df['Severity'] = df['Notes']
replace_dict = {'DTD':1,'DNP':2,'out indefinitely':3,'out for season':4}
df['Severity'] = df['Severity'].replace(replace_dict)

此部分:

lst = [[33, 428], [223, 691], [521, 53], [83, 96], [423, 614], [360, 311], [55, 66]]
regionNumber = [1, 2, 3, 4, 5, 6, 7]

lookup = {location : r for locations, r  in zip(lst, regionNumber) for location in locations }

df['region'] = df['location'].map(lookup)

print(df)

dictionary comprehension,(有关理解here的更多信息)。它是用于创建字典的Python表达式,等效于以下嵌套的for循环:

   location  region
0        33       1
1       223       2
2        66       7

答案 1 :(得分:-1)

尝试一下:

region_map = dict(zip(regionNumber, list))
df['region'] = df['location'].map(region_map)