我有一个看起来或多或少像这样的数据框:
import pandas as pd
df = pd.DataFrame([list('AAABBBAAA')]).T
df.columns = [ 'type']
print(df)
type
0 A
1 A
2 A
3 B
4 B
5 B
6 B
7 A
8 A
9 A
10 B
假设我的 DataFrame 已经排序,我的目标是沿着“类型”列识别“连续性”;我会对这样的事情感到高兴:
type portion_ID
0 A A0
1 A A0
2 A A0
3 B B0
4 B B0
5 B B0
6 B B0
7 A A1
8 A A1
9 A A1
10 B B1
我猜是这样的
df['portion_ID'] = g['type'].apply(lambda s: s + some_magics())
可以解决这个问题,但我没有在任何地方找到“some_magic()”:-)
提前致谢
最佳答案
我想到的第一件事是你可以在对象中保存状态:
class State(object):
def __init__(self):
self.current = None
self.current_label = None
self.types = {}
def func(row, state):
t = row['type']
if state.current != t:
state.current = t
state.types[t] = state.types.get(t, -1) + 1
state.current_label = t + str(state.types[t])
return state.current_label
>>> df.apply(func, args=(State(),), axis=1)
0 A0
1 A0
2 A0
3 B0
4 B0
5 B0
6 B0
7 A1
8 A1
9 A1
10 B1
dtype: object
如果状态发生变化,您还可以计算包含信息的列,然后仅传递字典作为状态:
df['change'] = ~ (df == df.shift())
def func(row, state):
t = row['type']
if row['change']:
state[t] = state.get(t, -1) + 1
return t + str(state[t])
df.apply(func, args=({},), axis=1)
关于python - pandas:沿着 DataFrame 识别 "portions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18617854/