如何追加多个pandas DataFrame(附实例)

352 阅读2分钟

你可以使用下面的基本语法来一次追加多个pandas DataFrame:

import pandas as pd

#append multiple DataFrames
df_big = pd.concat([df1,df2, df3], ignore_index=True) 

这个特殊的语法将把df1df2df3追加到一个名为df_big的单一pandas DataFrame中。

下面的例子展示了如何在实践中使用这种语法。

例子1:一次追加多个潘达斯数据框架

下面的代码展示了如何一次追加多个pandas DataFrames。

import pandas as pd

#create three DataFrames
df1 = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E'],
                    'points':[12, 5, 13, 17, 27]})

df2 = pd.DataFrame({'player': ['F', 'G', 'H', 'I', 'J'],
                    'points':[24, 26, 27, 27, 12]})

df3 = pd.DataFrame({'player': ['K', 'L', 'M', 'N', 'O'],
                    'points':[9, 5, 5, 13, 17]})

#append all DataFrames into one DataFrame
df_big = pd.concat([df1,df2, df3], ignore_index=True)

#view resulting DataFrame
print(df_big)

        player	points
0	A	12
1	B	5
2	C	13
3	D	17
4	E	27
5	F	24
6	G	26
7	H	27
8	I	27
9	J	12
10	K	9
11	L	5
12	M	5
13	N	13
14	O	17

结果是一个大的DataFrame,包含了三个单独DataFrame中的所有行。

参数ignore_index=True告诉pandas忽略每个DataFrame中的原始索引号,为新的DataFrame创建一个从0开始的新索引。

例如,考虑一下当我们在堆叠下面两个DataFrame时不使用ignore_index=True会发生什么。

import pandas as pd

#create two DataFrames with indices
df1 = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E'],
                    'points':[12, 5, 13, 17, 27]},
                    index=[0, 1, 2, 3, 4])

df2 = pd.DataFrame({'player': ['F', 'G', 'H', 'I', 'J'],
                    'points':[24, 26, 27, 27, 12]},
                    index=[2, 4, 5, 6, 9])

#stack the two DataFrames together
df_big = pd.concat([df1,df2])

#view resulting DataFrame
print(df_big)

        player	points
0	A	12
1	B	5
2	C	13
3	D	17
4	E	27
2	F	24
4	G	26
5	H	27
6	I	27
9	J	12

产生的DataFrame保留了这两个DataFrame的原始索引值。

一般来说,在附加多个DataFrame时,你应该使用ignore_index=True ,除非你有特殊的原因需要保留原来的索引值。

其他资源

如何向潘达斯数据框架添加空列
如何向潘达斯数据框架插入列
如何将潘达斯数据框架导出至Excel