Python 熊猫:使用其他列的迭代值添加新列
我有一个数据框,有两列——一列有单词,另一列有pos_标签Python 熊猫:使用其他列的迭代值添加新列,python,pandas,Python,Pandas,我有一个数据框,有两列——一列有单词,另一列有pos_标签 word1 tag1 0 Why WRB 1 is VBZ 2 this DT 3 happening NN 4 to TO 5 us PRP 6 Asterix NNP 7 and CC 8 Obelix NNP 如何再添加两列,其值为“word1”和“tag1”列的第(I+1)个值,以生
word1 tag1
0 Why WRB
1 is VBZ
2 this DT
3 happening NN
4 to TO
5 us PRP
6 Asterix NNP
7 and CC
8 Obelix NNP
如何再添加两列,其值为“word1”和“tag1”列的第(I+1)个值,以生成结果
word1 tag1 word2 tag2
0 Why WRB is VBZ
1 is VBZ this DT
2 this DT happening NNP
3 happening NNP to TO
4 to TO us PRP
5 us PRP Asterix NNP
6 Asterix NNP and CC
7 and CC Obelix NNP
8 Obelix NNP nan nan
通过调用并传递
-1
作为间隔来添加新列:
In [84]:
df['word2'], df['tag2'] = df['word1'].shift(-1), df['tag1'].shift(-1)
df
Out[84]:
word1 tag1 word2 tag2
0 Why WRB is VBZ
1 is VBZ this DT
2 this DT happening NN
3 happening NN to TO
4 to TO us PRP
5 us PRP Asterix NNP
6 Asterix NNP and CC
7 and CC Obelix NNP
8 Obelix NNP NaN NaN
通过调用并传递
-1
作为间隔来添加新列:
In [84]:
df['word2'], df['tag2'] = df['word1'].shift(-1), df['tag1'].shift(-1)
df
Out[84]:
word1 tag1 word2 tag2
0 Why WRB is VBZ
1 is VBZ this DT
2 this DT happening NN
3 happening NN to TO
4 to TO us PRP
5 us PRP Asterix NNP
6 Asterix NNP and CC
7 and CC Obelix NNP
8 Obelix NNP NaN NaN
在数据帧上使用shift(-1)
In [109]: df[['word2', 'tag2']] = df.shift(-1)
In [110]: df
Out[110]:
word1 tag1 word2 tag2
0 Why WRB is VBZ
1 is VBZ this DT
2 this DT happening NN
3 happening NN to TO
4 to TO us PRP
5 us PRP Asterix NNP
6 Asterix NNP and CC
7 and CC Obelix NNP
8 Obelix NNP NaN NaN
在数据帧上使用shift(-1)
In [109]: df[['word2', 'tag2']] = df.shift(-1)
In [110]: df
Out[110]:
word1 tag1 word2 tag2
0 Why WRB is VBZ
1 is VBZ this DT
2 this DT happening NN
3 happening NN to TO
4 to TO us PRP
5 us PRP Asterix NNP
6 Asterix NNP and CC
7 and CC Obelix NNP
8 Obelix NNP NaN NaN