「数据处理」pandas.concat() 合并数据集

concat()

The concat() function concatenates an arbitrary amount of Series or DataFrame objects along an axis while performing optional set logic (union or intersection) of the indexes on the other axes. Like numpy.concatenateconcat() takes a list or dict of homogeneously-typed objects and concatenates them.

df1 = pd.DataFrame(
    {
        "A": ["A0", "A1", "A2", "A3"],
        "B": ["B0", "B1", "B2", "B3"],
        "C": ["C0", "C1", "C2", "C3"],
        "D": ["D0", "D1", "D2", "D3"],
    },
    index=[0, 1, 2, 3],
)


df2 = pd.DataFrame(
    {
        "A": ["A4", "A5", "A6", "A7"],
        "B": ["B4", "B5", "B6", "B7"],
        "C": ["C4", "C5", "C6", "C7"],
        "D": ["D4", "D5", "D6", "D7"],
    },
    index=[4, 5, 6, 7],
)


df3 = pd.DataFrame(
    {
        "A": ["A8", "A9", "A10", "A11"],
        "B": ["B8", "B9", "B10", "B11"],
        "C": ["C8", "C9", "C10", "C11"],
        "D": ["D8", "D9", "D10", "D11"],
    },
    index=[8, 9, 10, 11],
)


frames = [df1, df2, df3]

result = pd.concat(frames)

result
Out[6]: 
      A    B    C    D
0    A0   B0   C0   D0
1    A1   B1   C1   D1
2    A2   B2   C2   D2
3    A3   B3   C3   D3
4    A4   B4   C4   D4
5    A5   B5   C5   D5
6    A6   B6   C6   D6
7    A7   B7   C7   D7
8    A8   B8   C8   D8
9    A9   B9   C9   D9
10  A10  B10  C10  D10
11  A11  B11  C11  D11

../_images/merging_concat_basic.png

Note

concat() makes a full copy of the data, and iteratively reusing concat() can create unnecessary copies. Collect all DataFrame or Series objects in a list before usingconcat().

frames = [process_your_file(f) for f in files]
result = pd.concat(frames)

Note

When concatenating DataFrame with named axes, pandas will attempt to preserve these index/column names whenever possible. In the case where all inputs share a common name, this name will be assigned to the result. When the input names do not all agree, the result will be unnamed. The same is true for MultiIndex, but the logic is applied separately on a level-by-level basis.

Joining logic of the resulting axis

The join keyword specifies how to handle axis values that don’t exist in the first DataFrame.

join='outer' takes the union of all axis values

df4 = pd.DataFrame(
    {
        "B": ["B2", "B3", "B6", "B7"],
        "D": ["D2", "D3", "D6", "D7"],
        "F": ["F2", "F3", "F6", "F7"],
    },
    index=[2, 3, 6, 7],
)


result = pd.concat([df1, df4], axis=1)

result
Out[9]: 
     A    B    C    D    B    D    F
0   A0   B0   C0   D0  NaN  NaN  NaN
1   A1   B1   C1   D1  NaN  NaN  NaN
2   A2   B2   C2   D2   B2   D2   F2
3   A3   B3   C3   D3   B3   D3   F3
6  NaN  NaN  NaN  NaN   B6   D6   F6
7  NaN  NaN  NaN  NaN   B7   D7   F7

../_images/merging_concat_axis1.png

join='inner' takes the intersection of the axis values

result = pd.concat([df1, df4], axis=1, join="inner")

result
Out[11]: 
    A   B   C   D   B   D   F
2  A2  B2  C2  D2  B2  D2  F2
3  A3  B3  C3  D3  B3  D3  F3

../_images/merging_concat_axis1_inner.png

To perform an effective “left” join using the exact index from the original DataFrame, result can be reindexed.

result = pd.concat([df1, df4], axis=1).reindex(df1.index)

result
Out[13]: 
    A   B   C   D    B    D    F
0  A0  B0  C0  D0  NaN  NaN  NaN
1  A1  B1  C1  D1  NaN  NaN  NaN
2  A2  B2  C2  D2   B2   D2   F2
3  A3  B3  C3  D3   B3   D3   F3

../_images/merging_concat_axis1_join_axes.png

Ignoring indexes on the concatenation axis

For DataFrame objects which don’t have a meaningful index, the ignore_index ignores overlapping indexes.

result = pd.concat([df1, df4], ignore_index=True, sort=False)

result
Out[15]: 
     A   B    C   D    F
0   A0  B0   C0  D0  NaN
1   A1  B1   C1  D1  NaN
2   A2  B2   C2  D2  NaN
3   A3  B3   C3  D3  NaN
4  NaN  B2  NaN  D2   F2
5  NaN  B3  NaN  D3   F3
6  NaN  B6  NaN  D6   F6
7  NaN  B7  NaN  D7   F7

../_images/merging_concat_ignore_index.png

Concatenating Series and DataFrame together

You can concatenate a mix of Series and DataFrame objects. The Series will be transformed to DataFrame with the column name as the name of the Series.

s1 = pd.Series(["X0", "X1", "X2", "X3"], name="X")

result = pd.concat([df1, s1], axis=1)

result
Out[18]: 
    A   B   C   D   X
0  A0  B0  C0  D0  X0
1  A1  B1  C1  D1  X1
2  A2  B2  C2  D2  X2
3  A3  B3  C3  D3  X3

../_images/merging_concat_mixed_ndim.png

Unnamed Series will be numbered consecutively.

s2 = pd.Series(["_0", "_1", "_2", "_3"])

result = pd.concat([df1, s2, s2, s2], axis=1)

result
Out[21]: 
    A   B   C   D   0   1   2
0  A0  B0  C0  D0  _0  _0  _0
1  A1  B1  C1  D1  _1  _1  _1
2  A2  B2  C2  D2  _2  _2  _2
3  A3  B3  C3  D3  _3  _3  _3

../_images/merging_concat_unnamed_series.png

ignore_index=True will drop all name references.

result = pd.concat([df1, s1], axis=1, ignore_index=True)

result
Out[23]: 
    0   1   2   3   4
0  A0  B0  C0  D0  X0
1  A1  B1  C1  D1  X1
2  A2  B2  C2  D2  X2
3  A3  B3  C3  D3  X3

../_images/merging_concat_series_ignore_index.png

Resulting keys#

The keys argument adds another axis level to the resulting index or column (creating a MultiIndex) associate specific keys with each original DataFrame.

result = pd.concat(frames, keys=["x", "y", "z"])

result
Out[25]: 
        A    B    C    D
x 0    A0   B0   C0   D0
  1    A1   B1   C1   D1
  2    A2   B2   C2   D2
  3    A3   B3   C3   D3
y 4    A4   B4   C4   D4
  5    A5   B5   C5   D5
  6    A6   B6   C6   D6
  7    A7   B7   C7   D7
z 8    A8   B8   C8   D8
  9    A9   B9   C9   D9
  10  A10  B10  C10  D10
  11  A11  B11  C11  D11

result.loc["y"]
Out[26]: 
    A   B   C   D
4  A4  B4  C4  D4
5  A5  B5  C5  D5
6  A6  B6  C6  D6
7  A7  B7  C7  D7

../_images/merging_concat_keys.png

The keys argument cane override the column names when creating a new DataFrame based on existing Series.

s3 = pd.Series([0, 1, 2, 3], name="foo")

s4 = pd.Series([0, 1, 2, 3])

s5 = pd.Series([0, 1, 4, 5])

pd.concat([s3, s4, s5], axis=1)
Out[30]: 
   foo  0  1
0    0  0  0
1    1  1  1
2    2  2  4
3    3  3  5

pd.concat([s3, s4, s5], axis=1, keys=["red", "blue", "yellow"])
Out[31]: 
   red  blue  yellow
0    0     0       0
1    1     1       1
2    2     2       4
3    3     3       5

You can also pass a dict to concat() in which case the dict keys will be used for the keysargument unless other keys argument is specified:

pieces = {"x": df1, "y": df2, "z": df3}

result = pd.concat(pieces)

result
Out[34]: 
        A    B    C    D
x 0    A0   B0   C0   D0
  1    A1   B1   C1   D1
  2    A2   B2   C2   D2
  3    A3   B3   C3   D3
y 4    A4   B4   C4   D4
  5    A5   B5   C5   D5
  6    A6   B6   C6   D6
  7    A7   B7   C7   D7
z 8    A8   B8   C8   D8
  9    A9   B9   C9   D9
  10  A10  B10  C10  D10
  11  A11  B11  C11  D11

../_images/merging_concat_dict.png

result = pd.concat(pieces, keys=["z", "y"])

result
Out[36]: 
        A    B    C    D
z 8    A8   B8   C8   D8
  9    A9   B9   C9   D9
  10  A10  B10  C10  D10
  11  A11  B11  C11  D11
y 4    A4   B4   C4   D4
  5    A5   B5   C5   D5
  6    A6   B6   C6   D6
  7    A7   B7   C7   D7

../_images/merging_concat_dict_keys.png

The MultiIndex created has levels that are constructed from the passed keys and the index of the DataFrame pieces:

result.index.levels
Out[37]: FrozenList([['z', 'y'], [4, 5, 6, 7, 8, 9, 10, 11]])

levels argument allows specifying resulting levels associated with the keys

result = pd.concat(
    pieces, keys=["x", "y", "z"], levels=[["z", "y", "x", "w"]], names=["group_key"]
)

result
Out[39]: 
                A    B    C    D
group_key                       
x         0    A0   B0   C0   D0
          1    A1   B1   C1   D1
          2    A2   B2   C2   D2
          3    A3   B3   C3   D3
y         4    A4   B4   C4   D4
          5    A5   B5   C5   D5
          6    A6   B6   C6   D6
          7    A7   B7   C7   D7
z         8    A8   B8   C8   D8
          9    A9   B9   C9   D9
          10  A10  B10  C10  D10
          11  A11  B11  C11  D11

../_images/merging_concat_dict_keys_names.png

result.index.levels
Out[40]: FrozenList([['z', 'y', 'x', 'w'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])

Appending rows to a DataFrame

If you have a Series that you want to append as a single row to a DataFrame, you can convert the row into a DataFrame and use concat()

s2 = pd.Series(["X0", "X1", "X2", "X3"], index=["A", "B", "C", "D"])

result = pd.concat([df1, s2.to_frame().T], ignore_index=True)

result
Out[43]: 
    A   B   C   D
0  A0  B0  C0  D0
1  A1  B1  C1  D1
2  A2  B2  C2  D2
3  A3  B3  C3  D3
4  X0  X1  X2  X3

../_images/merging_append_series_as_row.png

更多函数见https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

  • 15
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: pandas.concat 是一个函数,用于将多个 Pandas 数据框(DataFrame)或者 Pandas 系列(Series)按照指定的轴进行连接。它可以按照行或者列方向进行连接,具体实现方式取决于指定的轴参数。 语法如下: ``` pandas.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True) ``` 参数说明: - objs: 一个列表或者字典,里面包含了要连接的 Pandas 数据框或者 Pandas 系列。 - axis: 指定要连接的轴,0 表示按照行方向连接,1 表示按照列方向连接,默认为 0。 - join: 指定连接方式,可以是 'inner' 或者 'outer',默认为 'outer'。 - ignore_index: 如果为 True,则忽略原来数据框中的索引,重新生成一个新的索引。 - keys: 在连接多个数据框的时候,可以使用 keys 参数来指定每个数据框的标签,这样连接之后的数据框就会使用 MultiIndex 来表示。 - levels: 如果使用 keys 参数指定了标签,那么可以使用 levels 参数来指定每个标签的层级结构。 - names: 如果使用 keys 参数指定了标签,那么可以使用 names 参数来指定每个层级的名称。 - verify_integrity: 如果为 True,则在连接之前检查数据框中是否有重复的索引,如果有则抛出 ValueError 异常。 - sort: 如果为 True,则在连接之后对结果进行排序,默认为 False。 - copy: 如果为 True,则返回连接之后的新对象,否则返回原对象的视图。 示例: ``` import pandas as pd # 创建两个数据框 df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) df2 = pd.DataFrame({'A': [4, 5, 6], 'B': [7, 8, 9]}) # 将两个数据框按照行方向连接 result = pd.concat([df1, df2], axis=0) print(result) ``` 输出: ``` A B 0 1 4 1 2 5 2 3 6 0 4 7 1 5 8 2 6 9 ``` ### 回答2: pandas.concat是一个用于pandas库中合并数据的函数。它可以水平或垂直地连接不同的数据集,产生一个新的数据集pandas.concat函数可以接受多个数据集作为参数,并根据指定的轴进行连接。默认情况下,它会在轴0上进行连接,即垂直连接,将数据集按顺序堆叠起来。例如,如果我们有两个数据集df1和df2,通过pandas.concat([df1, df2])就可以将它们垂直连接起来。 此外,我们还可以通过指定axis参数来进行水平连接。当axis=1时,pandas.concat会将数据集在水平方向上连接起来。这意味着我们可以根据列名在水平方向上合并数据集,产生新的列。需要注意的是,进行水平连接时,数据集必须有相同的行索引,否则连接将会失败。 在进行连接时,pandas.concat还有其他一些重要的参数。其中,join用于指定连接的方式,默认为'outer',表示采用外连接,即保留所有行和列。如果选择'inner',则只保留两个数据集交集部分的行和列。另外,我们还可以通过keys参数为连接之后的数据集添加层次化索引。 总之,pandas.concat是一个非常有用的函数,可以将多个数据集合并成一个新的数据集,扩展数据分析的能力。无论是垂直连接还是水平连接,我们都可以根据实际需求选择适当的参数和方法。 ### 回答3: pandas.concat是一个在pandas库中用于合并/连接数据的函数。它可以将多个数据集按照指定的轴方向进行连接,产生一个新的数据集pandas.concat函数的常见用法是将具有相同结构的数据集进行拼接。例如,我们可以使用concat函数将两个具有相同列名的DataFrame对象连接成一个新的DataFrame对象。连接时可以指定连接的轴方向,默认为0,即按行进行拼接。我们还可以通过设置axis参数来指定为1,表示按列进行连接。 除了连接具有相同结构的数据集外,pandas.concat函数还可以用于连接具有不同结构的数据集。在这种情况下,我们可以使用join参数来指定连接方式,有inner、outer、left和right四种连接方式可供选择。默认情况下,join为outer,表示使用外连接的方式进行连接。 此外,pandas.concat函数还可以通过设置keys参数来为合并后的数据集增加层次化索引。如果我们传递一个列表给keys参数,合并后的数据集将具有多个层次的索引,其中每个层次对应一个列表中的元素。 总之,pandas.concat函数是一个非常灵活和强大的工具,它能够方便地处理数据集合并和连接操作,提供了多种参数和选项来满足不同的需求。使用这个函数可以轻松地将多个数据集合并成一个,为数据处理和分析提供了很大的便利性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值