假设我有一个数据框架
>> df = pd.DataFrame({'code': ['A', 'A', 'B', 'B', 'C', 'C', 'C', 'B', 'A', 'C', 'C', 'B' ]})
code
0 A
1 A
2 B
3 B
4 C
5 C
6 C
7 B
8 A
9 C
10 C
11 B
我想创建另一个列,它给出了相同值的下一个连续出现之前的代码项,以及前一个出现的目标索引。例如:
code target prev_idx
0 A [] NaN
1 A [] 0
2 B [] NaN
3 B [] 2
4 C [] NaN
5 C [] 4
6 C [] 5
7 B [C, C, C] 3
8 A [B, B, C, C, C, B] 1
9 C [B, A] 6
10 C [] 9
11 B [A, C, C] 7
最快的方法是什么?
def get_target(row,df=None):
"""
this function is applied to all rows in df
row.name is the index of the current row
row.code is the value in the code column
did row.code value appear ever before the current row?
if so return the segments starting from its last appearance till current row
"""
target = (df.code[:row.name]==row.code)
if target.any():
prev_idx = target[target].index[-1]
return {'target':df.code[prev_idx:row.name].tolist()[1:],
'prev_idx':prev_idx}
elif target.empty: # if this is the first row
return {'target':[],'prev_idx':-1}
# return the index of the previous row
return {'target':[],'prev_idx':target.shift().index[-1]}
df[['target','prev_idx']] = df.apply(get_target,df=df,axis=1,result_type='expand')
df
,
prev_idx03[' C ', ' C ', ' C '] 3[' B ', ' B ', ' C ', ' C ', ' C ', ' B '] ['B', 'A'][' A ', ' C ', ' C ']
另寻出路。对于我的实际应用程序(数千行),它比@tozCSS发布的答案要快,可能是因为我们不会每次都搜索整个数据框(target = (df.code[:row.name]==row.code)
)。作为奖励,即使索引不是从0
到len(df)
,它也可以工作。
def get_target(row, data, col):
if not row['first_of_seq']:
return []
else:
return data.iloc[data.index.get_loc(row['prev_idx'] + 1): data.index.get_loc(row.name)][col].tolist()
def get_elements_in_between(data, col):
data = data.copy()
# get the index of the previous occurrence of the item
old_idx_name = data.index.name
data = data.rename_axis('dummy_idx').reset_index()
data['prev_idx'] = data.groupby(col)['dummy_idx'].shift()
# check if the item is the first of consecutive occurrences or not
data['first_of_seq'] = ((data['prev_idx'] - data['dummy_idx']) != -1) & (~data['prev_idx'].isna())
# convert floats to integers (and NaN to <NA>)
data['prev_idx'] = data['prev_idx'].astype('Int64')
# revert to the original indexing
data = data.set_index('dummy_idx')
data = data.rename_axis(old_idx_name)
# get the targets using the target indices
data['target'] = data.apply(get_target, args=(data, col), axis=1)
data.drop(columns=['first_of_seq'], inplace=True)
return data
我们得到:
>> get_elements_in_between(df, 'code')
code prev_idx target
0 A <NA> []
1 A 0 []
2 B <NA> []
3 B 2 []
4 C <NA> []
5 C 4 []
6 C 5 []
7 B 3 [C, C, C]
8 A 1 [B, B, C, C, C, B]
9 C 6 [B, A]
10 C 9 []
11 B 7 [A, C, C]
相关内容
- 由非空格组成的字符索引系列
- pandas多级索引系列:索引值转换为数据框架列的名称
- 如何在Panda乘法中保留2个多索引系列的所有索引级别
- 使用类别索引值在特定级别上对多索引系列进行排序
- Pandas:更改多索引系列的重复项
- 将所有列设置为索引,或将数据帧转换为多索引系列
- 熊猫:日期时间索引系列到时间索引日期列数据帧
- Pandas多索引系列处理
- 熊猫多索引系列中的级别排序子集问题
- 将多索引系列透视到数据帧中
- 如何在熊猫中获取分层索引系列中值的索引
- 熊猫重新排列多索引系列
- 通过使用第二个索引作为列,将 pandas 多索引系列转换为数据帧
- 将多索引系列变成一系列dict
- Python Pandas 日期索引系列日期和时间转换为一个时区到另一个时区
- 多索引系列中的自定义聚合
- 熊猫划分了两个多索引系列
- 合并 Python 中多索引系列的列表
- 在 Python 中访问多索引系列中的值
- Pandas:保存到csv时的内存差异(数据帧与多索引系列)
最新更新
- Django模板-如何在子对象的forloop中显示子对象为null时显示父对象
- 如何处理在另一个屏幕中获取的数据?
- 当输入有效的成员号时未执行返回语句
- 检查两个字符串的相等性在javascript中不能正常工作
- 使用laravel从数组中获取值
- 升级到Expo SDK 48.0.10后,应用卡在启动界面
- 如何创建一个循环,输出给定的列表(包括数字)
- 所有的酒吧/蜡烛都在粉刷
- 这个字段是Django的哪个字段以及如何使用它?
- 使用# id更改HTML模板中的JS代码值
- Regex语句,用于捕获最外层括号内的元素
- 如何在用户猜测/输入后更改占位符?
- 是否有一种方法来创建一个DataFrame从特定的颜色编码行是在谷歌工作表?(长颈鹿和熊猫)
- AWS Glue: SCRAM认证需要libpq版本10或以上[Using CockroachDB]
- 如何使用信号协议加密/解密?
- pandas dataframe在特定列中的列表值满足一定条件时获取行
- &16 在此 MySQL 查询中做什么?
- 是否有办法使类名作为一个变量?.. Parent_class *p_derived = new classnameher
- 错误:未能将一些参考推入' path '
- 我如何让matplotlib正确格式化这些datetime64对象?
- 如何删除重复的行基于多列值在亚马逊雅典娜?
- 无法"npm install"项目
- Applescript在文件夹中搜索带有关键字的照片
- 在CocoaPods任务中运行管道时出错
- 我是如何设法在通常的 conf 设置之外定义一个 XAMPP Apache 额外目录的?找不到证据
- 我的主要分支是错误的,我想用另一个分支重写它,我怎么能做这样的事情?
- 防止在for循环中展开的函数的形参中展开变量
- 自动伸缩组实例未在ALB上注册
- 我有一个问题与基础SQLITE3,如何解决它?
- react useEffect(): Hello只记录一次
热门标签:
javascript python java c# php android html jquery c++ css ios sql mysql arrays asp.net json python-3.x ruby-on-rails .net sql-server django objective-c excel regex ruby linux ajax iphone xml vba spring asp.net-mvc database wordpress string postgresql wpf windows xcode bash git oracle list vb.net multithreading eclipse algorithm macos powershell visual-studio image forms numpy scala function api selenium