我有以下 df:
id1 id2 id3(expected_col)
21 4 21a
21 4 21a
21 4 21a
21 5 21b
22 6 22a
22 6 22a
22 6 22a
23 7 23a
23 7 23a
23 8 23b
23 9 23c
有两列 - id1 和 id2,我想创建一个新列生成 id3,它是前两列的组合。
整数部分与 id1 列相同,但我想添加每当 id2 更改时更改的字符串,然后每当新的 id1< 时字母循环再次从“a”开始/strong> 遇到了。
所以也许我们可以 grouby id1 然后执行其余操作,但我不确定如何为新列生成字符串字母表。上面的 df id3 是我期望的结果列。
如果有什么不清楚的地方请告诉我。
请您参考如下方法:
使用 GroupBy-Apply 方法,使用 shift , ne , 和 cumsum在“id2”的组级别使用以确定更改,然后映射到 ascii_lowercase字母。
from string import ascii_lowercase
def combine_ids(grp, letters):
grp = grp.ne(grp.shift()).cumsum() - 1
return str(grp.name) + grp.map(letters)
letters = pd.Series(list(ascii_lowercase))
df['id3'] = df.groupby('id1')['id2'].apply(combine_ids, letters)
以上假定您最多只需要附加 26 个字母。如果您需要更多,您可以使用类似于下面的过程来添加重复的字母 'aa' - 'zz':
from itertools import product
from string import ascii_lowercase
doubles = map(''.join, product(ascii_lowercase, repeat=2))
letters = pd.Series(list(ascii_lowercase) + list(doubles))
结果输出:
id1 id2 id3
0 21 4 21a
1 21 4 21a
2 21 4 21a
3 21 5 21b
4 22 6 22a
5 22 6 22a
6 22 6 22a
7 23 7 23a
8 23 7 23a
9 23 8 23b
10 23 9 23c
