如何添加两个 pandas dataframe(示例)


您可以使用以下基本语法将值添加到两个 pandas DataFrame 中:

 df3 = df1. add (df2, fill_value= 0 )

这将生成一个新的 DataFrame,其中包含每个 DataFrame 中匹配元素的总和。

如果一个元素存在于一个 DataFrame 而不是另一个 DataFrame 中,则现有元素将在生成的 DataFrame 中使用。

以下示例展示了如何在实践中使用此语法。

示例:如何添加两个 Pandas DataFrame

假设我们有以下两个 panda DataFrame:

 import pandas as pd

#create first DataFrame
df1 = pd. DataFrame ({' points ': [18, 22, 19, 14, 11],
                    ' assists ': [5, 11, 7, 9, 12]})

#view first DataFrame
print (df1)

   assist points
0 18 5
1 22 11
2 19 7
3 14 9
4 11 12

#create second DataFrame
df2 = pd. DataFrame ({' points ': [10, 5, 4, 3, 9, 14],
                    ' assists ': [9, 7, 4, 2, 3, 3]})

#view second DataFrame
print (df2)

   assist points
0 10 9
1 5 7
2 4 4
3 3 2
4 9 3
5 14 3

我们可以使用以下语法创建一个新的 DataFrame,该 DataFrame 获取每个 DataFrame 中匹配元素的总和:

 #create new DataFrame by adding two DataFrames
df3 = df1. add (df2, fill_value= 0 )

#view new DataFrame
print (df3)

   assist points
0 28.0 14.0
1 27.0 18.0
2 23.0 11.0
3 17.0 11.0
4 20.0 15.0
5 14.0 3.0

请注意,生成的 DataFrame 包含每个 DataFrame 中匹配元素的总和。

请注意,索引值为 5 的行仅存在于第二个 DataFrame 中,因此该行中的值只是第二个 DataFrame 中的值。

另请注意,由于我们进行了加法,因此新 DataFrame 中的每个值都表示为带有一位小数的浮点值。

要将这些值转换回整数,我们可以使用astype()函数:

 #convert all columns in new DataFrame to integer
df3 = df3. astype (' int64 ')

#view updated DataFrame
print (df3)

   assist points
0 28 14
1 27 18
2 23 11
3 17 11
4 20 15
5 14 3

新 DataFrame 中的每个值现在都是整数。

其他资源

以下教程解释了如何执行其他常见的 panda 任务:

Pandas:将一列从一个 DataFrame 添加到另一个 DataFrame
Pandas:获取不在另一个 DataFrame 中的行
Pandas:如何检查多列是否相等

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注