我正在尝试使用循环将 DataFrame 添加到现有的 DataFrame 中。目前,
new_data
每列有 4 个值。我想通过循环并添加新数据,即每次循环迭代时每列 3 个值。df2
最终结果每列应有 19 个值,例如
new_data = df = pd.DataFrame({"a":[1, 2, 3, 4],
"b":[5, 6, 7, 8]})
for i in range(len(5)):
df2 = pd.DataFrame({"a":[1, 2, 3],
"b":[5, 6, 7]})
print(df2)
new_data.append(df2)
但由于某种原因它不起作用,我很困惑。当我尝试在没有循环的情况下执行操作时,它工作正常。
例如:
a b
----
1 5
2 6
3 7
4 8
1 5
2 6
3 7
1 5
2 6
3 7
1 5
2 6
3 7
1 5
2 6
3 7
1 5
2 6
3 7
我不明白这里的问题是什么。请向我解释一下这里的问题是什么。
# Creating the first Dataframe using dictionary
df1 = df = pd.DataFrame({"a":[1, 2, 3, 4],
"b":[5, 6, 7, 8]})
# Creating the Second Dataframe using dictionary
df2 = pd.DataFrame({"a":[1, 2, 3],
"b":[5, 6, 7]})
# Print df1
print(df1, "\n")
df1.append(df2)
更好的是,不要使用即将被弃用的append,而是使用
df1 = df1.append(df2)
来代替:
concat
df1 = pd.concat([df1, df2])
根据您想要的时间复制数据帧
pd.concat
,而不是循环。只有这样,您才能将两个数据框连接在一起。df2
我认为这段代码会对你有帮助
replicate = 5
new_df2 = pd.concat([df2]*replicate)
pd.concat([new_data, new_df2], ignore_index=True)
Out[34]:
a b
0 1 5
1 2 6
2 3 7
3 4 8
4 1 5
5 2 6
6 3 7
7 1 5
8 2 6
9 3 7
10 1 5
11 2 6
12 3 7
13 1 5
14 2 6
15 3 7
16 1 5
17 2 6
18 3 7
我还写了一篇关于 pandas 的博客,如果您想了解有关 pandas 的更多信息,可以访问我的博客:-https://surushatutorials.blogspot.com/2024/02/python-pandas.html