如何将特定列拆分为 Pandas 中的新列?
How can I split a specific column to new columns in Pandas?
我想用逗号将 "rest" 列拆分为新列并删除 "R="。并将 +1 添加到 "joints" 列。我该怎么办?
df
joints rest
0 R=0,0,1,1,1,1
3 R=0,0,1,1,1,1
42 R=0,0,1,1,1,1
45 R=0,0,1,1,1,1
我想这样做:
joints U1 U2 U3 R1 R2 R3
1 0 0 1 1 1 1
4 0 0 1 1 1 1
43 0 0 1 1 1 1
46 0 0 1 1 1 1
对于更多动态重命名列名称,使用 lambda 函数,对于新列,使用 Series.str.split
with expand=True
and assign back to original by DataFrame.join
:
f = lambda x: f'U{x+1}' if x < 3 else f'R{x-2}'
df1 = (df.join(df.pop('rest').str.split('=')
.str[1]
.str.split(',', expand=True)
.rename(columns=f))
.assign(joints = df['joints'] + 1))
print (df1)
joints U1 U2 U3 R1 R2 R3
0 1 0 0 1 1 1 1
1 4 0 0 1 1 1 1
2 43 0 0 1 1 1 1
3 46 0 0 1 1 1 1
这是一种方法。由于没有为列命名指定标准,我在这种情况下只是硬编码:
cols = ['U1', 'U2', 'U3', 'R1', 'R2', 'R3']
out = (df.rest.str.lstrip('R=')
.str.split(',', expand=True)
.rename(columns=dict(zip(range(len(cols)), cols)))
out['joints'] = df.joints.add(1)
U1 U2 U3 R1 R2 R3 joints
0 0 0 1 1 1 1 1
1 0 0 1 1 1 1 4
2 0 0 1 1 1 1 43
3 0 0 1 1 1 1 46
我想用逗号将 "rest" 列拆分为新列并删除 "R="。并将 +1 添加到 "joints" 列。我该怎么办?
df
joints rest
0 R=0,0,1,1,1,1
3 R=0,0,1,1,1,1
42 R=0,0,1,1,1,1
45 R=0,0,1,1,1,1
我想这样做:
joints U1 U2 U3 R1 R2 R3
1 0 0 1 1 1 1
4 0 0 1 1 1 1
43 0 0 1 1 1 1
46 0 0 1 1 1 1
对于更多动态重命名列名称,使用 lambda 函数,对于新列,使用 Series.str.split
with expand=True
and assign back to original by DataFrame.join
:
f = lambda x: f'U{x+1}' if x < 3 else f'R{x-2}'
df1 = (df.join(df.pop('rest').str.split('=')
.str[1]
.str.split(',', expand=True)
.rename(columns=f))
.assign(joints = df['joints'] + 1))
print (df1)
joints U1 U2 U3 R1 R2 R3
0 1 0 0 1 1 1 1
1 4 0 0 1 1 1 1
2 43 0 0 1 1 1 1
3 46 0 0 1 1 1 1
这是一种方法。由于没有为列命名指定标准,我在这种情况下只是硬编码:
cols = ['U1', 'U2', 'U3', 'R1', 'R2', 'R3']
out = (df.rest.str.lstrip('R=')
.str.split(',', expand=True)
.rename(columns=dict(zip(range(len(cols)), cols)))
out['joints'] = df.joints.add(1)
U1 U2 U3 R1 R2 R3 joints
0 0 0 1 1 1 1 1
1 0 0 1 1 1 1 4
2 0 0 1 1 1 1 43
3 0 0 1 1 1 1 46