将多行熊猫DataFrame追加到新DataFrame中

时间:2019-06-08 20:20:29

标签: python pandas dataframe

我有一个当前数据框,如下所示:

   F1 , F2 , F3 , F4 , Label
   1  , 2  , 3  , 4  ,  Dog 
   2  , 3  , 4  , 5  ,  Cat
   3  , 4  , 5  , 6  ,  Cat
   4  , 5  , 6  , 7  ,  Dog 
   5  , 6  , 7  , 8  ,  Cat
   6  , 7  , 8  , 9  ,  Dog

               .
               . 
               . 
               . 

   1  , 2  , 3  , 4  ,  Dog

我想要的是遍历该数据帧,然后将接下来的3行合并为一行,然后再右移至另一数据帧,以便获得以下输出:

   F1 , F2 , F3 , F4 , Label , F1 , F2 , F3 , F4 , Label , F1 , F2 , F3 , F4 , Label
   1  , 2  , 3  , 4  ,  Dog  , 2  , 3  , 4  , 5  , Cat   , 3  , 4  , 5  , 6  ,  Cat
   2  , 3  , 4  , 5  ,  Cat  , 3  , 4  , 5  , 6  , Cat   , 4  , 5  , 6  , 7  ,  Dog
   3  , 4  , 5  , 6  ,  Cat  , 4  , 5  , 6  , 7  , Dog   , 5  , 6  , 7  , 8  ,  Cat
   4  , 5  , 6  , 7  ,  Dog  , 5  , 6  , 7  , 8  , Cat   , 6  , 7  , 8  , 9  ,  Dog

我知道最后两行将没有NaN值,但这无关紧要,因为我以后可以随时删除它们。

我的代码如下:

import pandas as pd
import numpy as np


path = r'C:\Users\Ahmed Ismail Khalid\Desktop\Research Paper\Training and Validation.csv'

df = pd.read_csv(path)
cols = ['Positive Score','Compound Score','Negative Score','Neutral Score','Class Label',
        'Positive Score','Compound Score','Negative Score','Neutral Score','Class Label',
        'Positive Score','Compound Score','Negative Score','Neutral Score','Class Label',
        'Positive Score','Compound Score','Negative Score','Neutral Score','Class Label',
        'Positive Score','Compound Score','Negative Score','Neutral Score','Class Label',
        'Positive Score','Compound Score','Negative Score','Neutral Score','Class Label',
        'Positive Score','Compound Score','Negative Score','Neutral Score','Class Label']
new_df = pd.DataFrame(columns=cols)


rows = []

for index, row in df.items() :
    row_m = df.iloc[index:index+6]
    rows.append(row_m)

new_df = pd.concat(rows,axis=1)

print(new_df)

我们将不胜感激。

预先感谢

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找类似的东西。

subdf = [df.iloc[i:i+len(df)-2].reset_index(drop=True) for i in range(3)]
ddf = pd.concat(subdf, axis=1)
print(ddf)

如果df是您作为示例给出的数据帧(我删除了逗号分隔符和最后一行),则上面的代码将输出:

   F1  F2  F3  F4 Label  F1  F2  F3  F4 Label  F1  F2  F3  F4 Label
0   1   2   3   4   Dog   2   3   4   5   Cat   3   4   5   6   Cat
1   2   3   4   5   Cat   3   4   5   6   Cat   4   5   6   7   Dog
2   3   4   5   6   Cat   4   5   6   7   Dog   5   6   7   8   Cat
3   4   5   6   7   Dog   5   6   7   8   Cat   6   7   8   9   Dog

如果在正确的行上停止选择,则无需删除NaN值(这是-2i+len(df)-2的目的)。
还请注意reset.index(drop=True)的使用:切片的数据帧需要忘记其原始索引,否则pd.concat稍后将在每行上附加其原始索引。 drop=True阻止添加包含原始索引的列index

相关问题