我有 1 号数据帧
给事物定价
0 1 笔
1 2 铅笔
2 6 苹果
我有 2 号数据帧:
给事物定价
0 5 笔
1 6 支铅笔
2 10 杯
我想加入两个 DataFrame,我想看到这个 DataFrame:
DataFrame 编号 1 + DatFrame 编号 2
给事物定价
0 6 笔
1支8号铅笔
2 6 苹果
3 10 杯
我该怎么做?
这段代码:
import pandas as pd
df = pd.DataFrame({'Things': ['pen', 'pencil'], 'Price': [1, 2]})
series = pd.Series([1,2], index=[0,1])
df["Price"] = series
df.loc[2] = [6, "apple"]
print("DataFrame number 1")
print(df)
df2 = pd.DataFrame({'Things': ['pen', 'pencil'], 'Price': [1, 2]})
series = pd.Series([5,6], index=[0,1])
df2["Price"] = series
df2.loc[2] = [10, "cup"]
print("DataFrame number 2")
print(df2)
最佳答案
您还可以使用concatenate 函数
沿axis = 0
组合两个dataframes
,然后group by
列并对它们求和
。
df3 = pd.concat([df, df2], axis=0).groupby('Things').sum().reset_index()
df3
输出:
Things Price
0 apple 6
1 cup 10
2 pen 6
3 pencil 8
关于python - 如何添加两个DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606317/