如何添加两个数据帧

2024-06-01 12:53:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有1号数据帧

定价

0 1笔

12支铅笔

26苹果

我有2号数据帧:

定价

0 5笔

16支铅笔

2 10杯

我想连接两个数据帧,我想看看这个数据帧:

数据帧编号1+数据帧编号2

定价

0 6笔

18支铅笔

26苹果

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)

Tags: 数据苹果dataframedfprice编号seriespd
3条回答

您还可以使用concatenate function将两个dataframes沿着axis = 0组合,然后group by列和{}它们组合在一起。在

df3 = pd.concat([df, df2], axis=0).groupby('Things').sum().reset_index()
df3

输出:

^{pr2}$

您可以合并、添加和删除临时列:

common = pd.merge(
    df,
    df2,
    on='Things',
    how='outer').fillna(0)
common['Price'] = common.Price_x + common.Price_y
common.drop(['Price_x', 'Price_y'], axis=1, inplace=True)
>>> common
    Things  Price
0   pen 6.0
1   pencil  8.0
2   apple   6.0
3   cup 10.0

您还可以将Things设置为两个数据帧的索引,然后使用^{}

df.set_index('Things').add(df2.set_index('Things'), fill_value=0).reset_index()

#  Things   Price
#0  apple    6.0
#1    cup   10.0
#2    pen    6.0
#3 pencil    8.0

相关问题 更多 >