繁体   English   中英

按开始值和结束值对 pandas dataframe 列进行切片

[英]Slice pandas dataframe column by start and end values

例如,我有一个看起来像这样的 dataframe:

0       -- end
1       QQQQ
2       GEO
3       DEF
4       ABC
5       -- start
6       -- end
7       apple
8.      -- start

是否可以通过“--end”和“--start”动态地对列进行切片。 意思是,我想独立处理 -- start 和 -- end 之间的数据。

start_end = df[df.col.str.contains('-- end')+1:df.col.str.contains('-- start')]

无济于事,也许这在 pandas 中甚至是不可能的,但我会喜欢输入。

谢谢你们。

您可以尝试如下:

data = {'column': {0: '-- end',
  1: 'QQQQ',
  2: 'GEO',
  3: 'DEF',
  4: 'ABC',
  5: '-- start',
  6: '-- end',
  7: 'apple',
  8: '-- start'}}

df = pd.DataFrame(data)

exclude_lst = ['-- start','-- end']

# get False for members of exclude_lst, True for the rest
bools = ~df.column.isin(['-- start','-- end'])

# get sequences: [1, 2, 2, 2, 2, 3, 3, 4, 5]
sequences = (bools != bools.shift()).cumsum()

# keep only sequences where bools == True (so, only 2 and 4)
groups = df[bools].groupby([sequences])

# now you can loop through each slice, and perform some operation on them
for gr in groups:
    print(gr)
    
# or put them in a list and go from there:
gr_lst = list(groups)

print(gr_lst[0])

(2,   column
1   QQQQ
2    GEO
3    DEF
4    ABC)

# so, we end up with tuples. Here gr_lst[0][0] == 2, a ref to first slice as [2, 2, 2, 2]

# use gr_lst[i][1] to access an actual slice, e.g.:
print(gr_lst[1][1])

  column
7  apple

暂无
暂无

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

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