首页 > 解决方案 > 当现有列'B'的连续5个单元格值是python中数据框的空白时,将标志分配给新列'A'

问题描述

我必须根据其他现有列的单元格值将标志分配给新列。

示例:如果一列的 5 个单元格值连续为空白,则新列的标志将为“text-1”,否则为“text-2”。

在此处输入图像描述

标签: pythonpandasdataframe

解决方案


你可以试试这个:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Column B':['a','bc','d','','','ef','df','','','','','','fg']})
df['Column A'] = np.where(df['Column B'].groupby((df['Column B'] != df['Column B'].shift()).cumsum()).transform(len) >= 5,'text-1','text-2')

   Column B Column A
0         a   text-2
1        bc   text-2
2         d   text-2
3             text-2
4             text-2
5        ef   text-2
6        df   text-2
7             text-1
8             text-1
9             text-1
10            text-1
11            text-1
12       fg   text-2

推荐阅读