Python 添加合并数据帧
添加两个数据帧内容的最佳方法是什么,这两个数据帧的索引基本相同: df1:Python 添加合并数据帧,python,pandas,dataframe,merge,Python,Pandas,Dataframe,Merge,添加两个数据帧内容的最佳方法是什么,这两个数据帧的索引基本相同: df1: A B C A 0 3 1 B 3 0 2 C 1 2 0 df2: df1+df2= A B C D A 0 4 2 0 B 4 0 5 2 C 2 5 0 0 D 0 2 0 0 我想你可以加上: In [625]: df1.add(df2,fill_value=0
A B C
A 0 3 1
B 3 0 2
C 1 2 0
df2:
df1+df2=
A B C D
A 0 4 2 0
B 4 0 5 2
C 2 5 0 0
D 0 2 0 0
我想你可以加上:
In [625]: df1.add(df2,fill_value=0)
Out[625]:
A B C D
A 0.0 4.0 2.0 0.0
B 4.0 0.0 5.0 2.0
C 2.0 5.0 0.0 0.0
D 0.0 2.0 0.0 0.0
您还可以同时使用这两个数据帧,因为串联(默认情况下)是按索引进行的
# sample dataframe
df1 = pd.DataFrame({'a': [1,2,3], 'b':[2,3,4]}, index=['a','c','e'])
df2 = pd.DataFrame({'a': [10,20], 'b':[11,22]}, index=['b','d'])
new_df= pd.concat([df1, df2]).sort_index()
print(new_df)
a b
a 1 2
b 10 11
c 2 3
d 20 22
e 3 4
# sample dataframe
df1 = pd.DataFrame({'a': [1,2,3], 'b':[2,3,4]}, index=['a','c','e'])
df2 = pd.DataFrame({'a': [10,20], 'b':[11,22]}, index=['b','d'])
new_df= pd.concat([df1, df2]).sort_index()
print(new_df)
a b
a 1 2
b 10 11
c 2 3
d 20 22
e 3 4