Pandas DataFrame merge() 方法
实例
使用另一个 DataFrame 的内容更新一个 DataFrame 的内容:
import pandas as pddata1 = {"name": ["Sally", "Mary", "John"],"age": [50, 40, 30]}data2 = {"name": ["Sally", "Peter", "Micky"],"age": [77, 44, 22]}df1 = pd.DataFrame(data1)df2 = pd.DataFrame(data2)newdf = df1.merge(df2, how='right')print(newdf)
定义与用法
merge() 方法通过使用指定的方法将两个 DataFrame 合并在一起来更新它们的内容。
使用这些参数可以控制要保留和替换的值。
语法
dataframe.merge(right, how, on, left_on, right_on, left_index, right_index, sort, suffixes, copy, indicator, validate)
参数
除了 right以外,所有参数都是关键字参数。
| 参数 | 值 | 描述 |
|---|---|---|
| right | 必填。一个 DataFrame,一个要合并的 Series | |
| how | 'left' 'right' 'outer' 'inner' 'cross' | 可选。 默认值 'inner'。 指定如何合并 |
| on | String List | 可选。 Specifies in what level to do the merging |
| left_on | String List | 可选。 Specifies in what level to do the merging on the DataFrame to the left |
| right_on | String List | 可选。 Specifies in what level to do the merging on the DataFrame to the right |
| left_index | True False | 可选。 Default False。 Whether to use the index from the leftDataFrame as join key or not |
| right_index | True False | 可选。 Default False。 Whether to use the index from the right DataFrame as join key or not |
| sort | True False | 可选。 Default False。 Specifies whether to sort the DataFrame by the join key or not |
| suffixes | List | 可选。 Default '_x', '_y''。 Specifies a list of strings to add for overlapping columns |
| copy | True False | 可选。 Default True。 Specifies whether to keep copies or not |
| indicator | True False String | 可选。 Default False。 Specifies whether to add a column in the DataFrame with information about the source of each row |
| validate | String | 可选。 Checks if the mergin is of a specified type |
返回值
一个新的带有合并结果的 DataFrame。
此方法不会更改原始 DataFrame。