Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.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 删除列中的空白以在列上创建_Python_Pandas - Fatal编程技术网

Python 删除列中的空白以在列上创建

Python 删除列中的空白以在列上创建,python,pandas,Python,Pandas,我有一些数据看起来像 pd.DataFrame([ {'col1': 'x', 'col2': 'name_x', 'col3': '', 'col4': '', 'col5': '', 'col6': ''}, {'col1':'', 'col2':'', 'col3': 'y', 'col4':'name_y', 'col5': '', 'col6':''}, {'col1':'', 'col2':'', 'col3': 'yy', 'col4':'name_yy',

我有一些数据看起来像

pd.DataFrame([
    {'col1': 'x', 'col2': 'name_x', 'col3': '', 'col4': '', 'col5': '', 'col6': ''},
    {'col1':'', 'col2':'', 'col3': 'y', 'col4':'name_y', 'col5': '', 'col6':''},
    {'col1':'', 'col2':'', 'col3': 'yy', 'col4':'name_yy', 'col5': '', 'col6':''},
    {'col1':'', 'col2':'', 'col3': '', 'col4':'', 'col5': 'z', 'col6':'name_z'},
    {'col1':'xx', 'col2':'name_xx', 'col3': '', 'col4':'', 'col5': '', 'col6':''},
    {'col1':'', 'col2':'', 'col3': 'yyy', 'col4':'name_yyy', 'col5': '', 'col6':''}
])

   col1  col2   col3    col4    col5    col6
0   x   name_x              
1                y     name_y       
2                yy    name_yy      
3                                z  name_z
4   xx  name_xx             
5                yyy   name_yyy         
我需要将所有数据推送到最左边的列,即
col1
col2

最终数据应如下所示:

    col1    col2
0   x   name_x
1   y   name_y
2   yy  name_yy
3   z   name_z
4   xx  name_xx
5   yyy name_yyy
印刷品:

col1 col2 col3 col4 col5 col6
0 x名称\u x
1 y姓名(y)
2 yy名称_yy
3 z名称_z
4 xx名称\u xx
5 yyy名称\u yyy
如果您想要这两列,那么您可以在之后执行
打印(df[[“col1”,“col2”]])

out = (df.agg(" ".join, axis=1)
         .str.split(expand=True)
         .rename(columns={0: "col1", 1: "col2"}))
agg
使用
join
对行进行重新分级,然后使用空格对行进行拆分,最后为输出重命名列

得到

  col1      col2
0    x    name_x
1    y    name_y
2   yy   name_yy
3    z    name_z
4   xx   name_xx
5  yyy  name_yyy

工作请客,谢谢:)
  col1      col2
0    x    name_x
1    y    name_y
2   yy   name_yy
3    z    name_z
4   xx   name_xx
5  yyy  name_yyy