Pandasd的串接作业

2024-04-19 03:50:56 发布

您现在位置:Python中文网/ 问答频道 /正文

有11列的pandas df需要使用regex修改前3列,并添加一个新的列和这个修改后的列,我们这是下游连接,像这样我需要保持这些列的元素不变,使其成为唯一的字符串

column1 column2 column3 column4 ...column 11

需要做这个新的_col=column1:column2-column3(column4)

做这个新专栏

^{pr2}$

我可以用简单的python一行代码来完成,不知道pandas的语法是什么

l = cols[0] + ":" + cols[1] + "-" + cols[2] + "(" + cols[5] + ")"

Tags: 字符串代码元素pandasdfcolumncolregex
3条回答

根据最近删除的一个答案,这个方法很好:

df1 = pd.DataFrame({
    'chrom': ['a', 'b', 'c'], 
    'start': ['d', 'e', 'f'], 
    'end': ['g', 'h', 'i'], 
    'strand': ['j', 'k', 'l']}
)
df1['unique_col'] = df1.chrom + ':' + df1.start + '-' + df1.end + '(' + df1.strand + ')'

听起来你的原始数据帧可能不包含字符串。如果它包含数字,则需要如下所示:

^{pr2}$

考虑数据帧df

np.random.seed([3,1415])
df = pd.DataFrame(np.random.choice(a, (5, 10))).add_prefix('col ')

print(df)

  col 0 col 1 col 2 col 3 col 4 col 5 col 6 col 7 col 8 col 9
0     Q     L     C     K     P     X     N     L     N     T
1     I     X     A     W     Y     M     W     A     C     A
2     U     Z     H     T     N     S     M     E     D     T
3     N     W     H     X     N     U     F     D     X     F
4     Z     L     Y     H     M     G     E     H     W     S

构造一个自定义的format函数

^{pr2}$

并应用于df

df.astype(str).apply(f, 1)

0    L:C-K(P)
1    W:A-C(A)
2    W:H-X(N)
3    E:H-W(S)
4    Y:E-P(N)
dtype: object

使用assign添加新列

df.assign(New=df.astype(str).apply(f, 1))
# assign in place with
# df['New'] = df.astype(str).apply(f, 1)

  col 0 col 1 col 2 col 3 col 4 col 5 col 6 col 7 col 8 col 9       New
0     Q     L     C     K     P     X     N     L     N     T  L:C-K(P)
1     I     X     A     W     Y     M     W     A     C     A  X:A-W(Y)
2     U     Z     H     T     N     S     M     E     D     T  Z:H-T(N)
3     N     W     H     X     N     U     F     D     X     F  W:H-X(N)
4     Z     L     Y     H     M     G     E     H     W     S  L:Y-H(M)

或者您可以将其打包成另一个对pd.Series进行操作的函数。这要求您以正确的顺序传递列。在

def u(a, b, c, d):
    return a + ':' + b + '-' + c + '(' + d + ')'

df.assign(New=u(df['col 1'], df['col 2'], df['col 3'], df['col 4']))
# assign in place with
# df['New'] = u(df['col 1'], df['col 2'], df['col 3'], df['col 4'])

  col 0 col 1 col 2 col 3 col 4 col 5 col 6 col 7 col 8 col 9       New
0     Q     L     C     K     P     X     N     L     N     T  L:C-K(P)
1     I     X     A     W     Y     M     W     A     C     A  X:A-W(Y)
2     U     Z     H     T     N     S     M     E     D     T  Z:H-T(N)
3     N     W     H     X     N     U     F     D     X     F  W:H-X(N)
4     Z     L     Y     H     M     G     E     H     W     S  L:Y-H(M)

只要所有列都包含字符串,您就可以使用您发布的相同语法来完成它。在

也可以使用^{}方法。在

df['new_col'] = cols[0].str.cat(':' + cols[1] + '-' + cols[2] + '(' + cols[5]+ ')')

相关问题 更多 >