Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将多个数据帧追加到一个数据帧中_Python_Pandas - Fatal编程技术网

Python 如何将多个数据帧追加到一个数据帧中

Python 如何将多个数据帧追加到一个数据帧中,python,pandas,Python,Pandas,我写了一段代码,将几个虚拟数据帧附加到一个数据帧中。追加后,预期的“DataFrame.shape”将是(9x3)。但是我的代码产生了一些意想不到的输出(6x3)。如何更正代码中的错误 import pandas as pd a = [[1,2,4],[1,3,4],[2,3,4]] b = [[1,1,1],[1,6,4],[2,9,4]] c = [[1,3,4],[1,1,4],[2,0,4]] d = [[1,1,4],[1,3,4],[2,0,4]] df1 = pd.Data

我写了一段代码,将几个虚拟数据帧附加到一个数据帧中。追加后,预期的“DataFrame.shape”将是(9x3)。但是我的代码产生了一些意想不到的输出(6x3)。如何更正代码中的错误

import pandas as pd


a = [[1,2,4],[1,3,4],[2,3,4]]
b = [[1,1,1],[1,6,4],[2,9,4]]
c = [[1,3,4],[1,1,4],[2,0,4]]
d = [[1,1,4],[1,3,4],[2,0,4]]


df1 = pd.DataFrame(a,columns=["a","b","c"])
df2 = pd.DataFrame(b,columns=["a","b","c"])
df3 = pd.DataFrame(c,columns=["a","b","c"])

for df in (df1, df2, df3):
    df =  df.append(df, ignore_index=True)
print df
我不想使用“pd.concat”,因为在这种情况下,我必须将所有数据帧存储到内存中,而我的真实数据集包含数百个具有巨大形状的数据帧。我只是想要一个代码,可以打开一个CSV文件一次进入循环更新与循环的进展最终DF


谢谢

首先使用
concat
连接一组dfs,速度更快:

In [308]:
df = pd.concat([df1,df2,df3], ignore_index=True)
df

Out[308]:
   a  b  c
0  1  2  4
1  1  3  4
2  2  3  4
3  1  1  1
4  1  6  4
5  2  9  4
6  1  3  4
7  1  1  4
8  2  0  4
其次,您在循环中重用iterable,这就是它覆盖它的原因,如果您这样做,它将工作:

In [307]:
a = [[1,2,4],[1,3,4],[2,3,4]]
b = [[1,1,1],[1,6,4],[2,9,4]]
c = [[1,3,4],[1,1,4],[2,0,4]]
d = [[1,1,4],[1,3,4],[2,0,4]]
​
​
df1 = pd.DataFrame(a,columns=["a","b","c"])
df2 = pd.DataFrame(b,columns=["a","b","c"])
df3 = pd.DataFrame(c,columns=["a","b","c"])
​
df = pd.DataFrame()
​
for d in (df1, df2, df3):
    df =  df.append(d, ignore_index=True)
df

Out[307]:
   a  b  c
0  1  2  4
1  1  3  4
2  2  3  4
3  1  1  1
4  1  6  4
5  2  9  4
6  1  3  4
7  1  1  4
8  2  0  4
在这里,我将iterable更改为
d
,并在循环外声明了一个空
df

df = pd.DataFrame()
​
for d in (df1, df2, df3):
    df =  df.append(d, ignore_index=True)

使用
concat
df=pd.concat([df1,df2,df3],ignore_index=True)
同样,您在循环
中为df-in(df1,df2,df3):df=df.append(df,ignore_index=True)重用iterable
那么它应该work@EdChum我已经更新了查询。我发布了代码,演示了如何使用
concat
,还向您展示了代码不起作用的原因