gpt4 book ai didi

python - 将 Pandas DataFrame 的多行追加到新的 DataFrame 中

转载 作者:行者123 更新时间:2023-12-01 07:44:54 24 4
gpt4 key购买 nike

我的当前数据框如下:

   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)

任何和所有帮助将不胜感激。

提前致谢

最佳答案

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

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 值(这就是 i+len(df) 中 -2 的用途-2)。
另请注意 reset.index(drop=True) 的使用:切片数据帧需要忘记其原始索引,否则 pd.concat 稍后会将每一行附加到其原始索引指数。 drop=True 阻止添加包含原始索引的列 index

关于python - 将 Pandas DataFrame 的多行追加到新的 DataFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509842/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com