Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/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 Pandas explode使用空单元格创建行_Python_Pandas_Split_Explode - Fatal编程技术网

Python Pandas explode使用空单元格创建行

Python Pandas explode使用空单元格创建行,python,pandas,split,explode,Python,Pandas,Split,Explode,我对熊猫不熟悉。我正在尝试将字符串拆分为多行。 我将它拆分成一个列表,然后尝试将其分解。 当我分解一个列表时,我得到一行,其中有一个空值,这是我不想要的 df = df.assign( col_a=df["col_a"].str.split("X:") ).explode("col_a") 变成: col_a col_b ...lots of columns with differe

我对熊猫不熟悉。我正在尝试将字符串拆分为多行。
我将它拆分成一个列表,然后尝试将其分解。 当我分解一个列表时,我得到一行,其中有一个空值,这是我不想要的

df = df.assign(
    col_a=df["col_a"].str.split("X:")
).explode("col_a")
变成:

col_a                col_b        ...lots of columns with different things
                     a
X: word1             a
X: word2             a
                     b
X: word2             b
X: word3             b
                     c
X: word2             c

我想要像这样的东西:

col_a                col_b        ...lots of columns with different things
word1                a
word2                a
word2                b
word3                b
word2                c
我该怎么处理这些空牢房?我一点也不想要那些排


谢谢

您可以尝试在
拆分之前删除起始
X:

df.assign(
  col_a = df.col_a.str.replace('^X: ', '').str.split(' X: ')
).explode('col_a')

#   col_a col_b
#0  word1     a
#0  word2     a
#1  word2     b
#1  word3     b
#2  word2     c

这是因为当您拆分字符串时,列表看起来像
[,word1,word2]
df.assign(
  col_a = df.col_a.str.replace('^X: ', '').str.split(' X: ')
).explode('col_a')

#   col_a col_b
#0  word1     a
#0  word2     a
#1  word2     b
#1  word3     b
#2  word2     c