python - Pandas 根据索引值分配标签

标签 python pandas

我有一个带有索引和多列的数据框。其次,我有几个包含根据某些标准采样的索引值的列表。现在我想根据特定行的索引是否存在于指定列表中的事实来创建带有标签的列。

现在我使用它有两种情况:

1) 创建一列并根据一个列表给出标签:

df['1_name'] = df.index.map(lambda ix: 'A' if ix in idx_1_model else 'B')

2) 创建列并根据多个列表给出标签:

def assignLabelsToSplit(ix_, random_m, random_y, model_m, model_y):
    if (ix_ in random_m) or (ix_ in model_m):
        return 'A'
    if (ix_ in random_y) or (ix_ in model_y):
        return 'B'
    else:
        return 'not_assigned'

df['2_name'] = df.index.map(lambda ix: assignLabelsToSplit(ix, idx_2_random_m, idx_2_random_y, idx_2_model_m, idx_2_model_y))

这可以工作,但速度很慢。每次调用大约需要 3 分钟,考虑到我必须多次执行函数,它需要更快。

感谢您的任何建议。

最佳答案

我认为你需要双 numpy.whereIndex.isin :

df['2_name'] = np.where(df.index.isin(random_m + model_m), 'A',
               np.where(df.index.isin(random_y + model_y), 'B', 'not_assigned'))

示例:

np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(10,1)), columns=['A'])
#print (df)

random_m = [0,1]
random_y =  [2,3]
model_m = [7,4]
model_y = [5,6]

print (type(random_m))
<class 'list'>

print (random_m + model_m)
[0, 1, 7, 4]

print (random_y + model_y)
[2, 3, 5, 6]

df['2_name'] = np.where(df.index.isin(random_m + model_m), 'A',
               np.where(df.index.isin(random_y + model_y), 'B', 'not_assigned'))
print (df)
   A        2_name
0  8             A
1  8             A
2  3             B
3  7             B
4  7             A
5  0             B
6  4             B
7  2             A
8  5  not_assigned
9  2  not_assigned

关于python - Pandas 根据索引值分配标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44880469/

相关文章:

python - (可能分组)行值到列

python - 从几个大型 Pandas 数据帧中有效地提取一些值

python - 如何使用 "rolling(window)"找到每批最频繁的值?

python - 按 MultiIndex 的一级对 pandas DataFrame 进行排序

python - 从任务栏隐藏应用程序

python - 如何从 SonarQube 测试覆盖范围中排除 `if __name__ == ' __main_ _':` 下的代码

python - 如何使用 Tweepy API 从推文中获取 media_url

python - 如何在 Python 中自动化 __special_methods__ 的委托(delegate)?

python - python 中用于电子邮件解析的正则表达式

python - 使用 numpy ufuncs 就地修改 Pandas 数据框