我有DataFrame编号1
价格事物
0 1笔
1 2支铅笔
2 6苹果
我有DataFrame编号2:
价格事物
0 5笔
1 6支铅笔
2 10杯
我想加入两个DataFrame,我想看看这个DataFrame:
DataFrame number 1 + DatFRame number 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)
答案 0 :(得分:2)
您还可以使用sizeof(DynamicArray) = sizeof(int*)
将两个sizeof DynamicArray
合并到concatenate function
,然后合并dataframes
列,axis = 0
。
group by
输出:
sum
答案 1 :(得分:1)
您可以合并,添加,然后删除临时列:
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
答案 2 :(得分:1)
您还可以将 Things 设置为两个数据框的索引,然后使用add(..., fill_value=0)
:
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