Python 3.x 分解一列并修改另一列

Python 3.x 分解一列并修改另一列,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,拥有如下数据集: df = pd.DataFrame(np.array([[1, 1, "this is"], [1, 2, "a sample"], [2, 1, "dataset"]]), columns=['row', 'col', 'word']) row col word 0 1 1 this is 1 1 2 a sample 2

拥有如下数据集:

df = pd.DataFrame(np.array([[1, 1, "this is"], [1, 2, "a sample"], [2, 1, "dataset"]]),
                   columns=['row', 'col', 'word'])

  row   col       word
0   1     1    this is
1   1     2   a sample
2   2     1    dataset
我想根据空格字符分解列word,并更新列col

因此,在这种情况下,预期的结果数据集是:

  row   col       word
0   1     1       this
1   1     2         is
2   1     3          a
3   1     4     sample
2   2     1    dataset
可通过应用以下方法实现基于空白字符的分解:

df.assign(word=df['word'].str.split(' ')).explode('word', ignore_index=True)

  row   col      word
0   1     1      this
1   1     1        is
2   1     2         a
3   1     2    sample
4   2     1   dataset
但问题是,col显然没有更新。关于如何实现这一点有什么想法吗?

让我们试试
groupby().cumcount()

输出:

  row  col     word
0   1    1     this
1   1    2       is
2   1    3        a
3   1    4   sample
4   2    1  dataset

你的预期产出是多少?
  row  col     word
0   1    1     this
1   1    2       is
2   1    3        a
3   1    4   sample
4   2    1  dataset