Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Pandas中将特定列拆分为新列?_Python_Python 3.x_Pandas_Dataframe_Columnsorting - Fatal编程技术网

Python 如何在Pandas中将特定列拆分为新列?

Python 如何在Pandas中将特定列拆分为新列?,python,python-3.x,pandas,dataframe,columnsorting,Python,Python 3.x,Pandas,Dataframe,Columnsorting,我想用逗号将“rest”列拆分为新列,并删除“R=”。并在“关节”列中添加+1。我该怎么办 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

我想用逗号将“rest”列拆分为新列,并删除“R=”。并在“关节”列中添加+1。我该怎么办

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函数,对于新列,重命名列名称用于
expand=True
,并通过以下方式分配回原始列:

f=lambda x:f'U{x+1}'如果x<3否则f'R{x-2}'
df1=(df.join(df.pop('rest').str.split('='))
.str[1]
.str.split(“,”,expand=True)
.重命名(列=f))
.分配(关节=df[“关节”]+1))
打印(df1)
接头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
列中的值是否为字符串值?您可以通过运行
df.dtypes
了解如何将0更改为“否”,将1更改为“是”@Abdurrahman-Use
df=df.replace({0':'No',1':'Yes'))
在我的代码之后
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