【发布时间】:2014-10-28 15:37:30
【问题描述】:
我有以下带有数据框的字典
A = pd.DataFrame([[2, 1], [2, 1], [2, 1]], columns=['A', 'B'], index = [1, 2, 3])
B = pd.DataFrame([[1, 1], [2, 2], [3, 3]], columns=['A', 'B'], index = [1, 2, 3])
C = pd.DataFrame([[1, 2], [1, 2], [1, 2]], columns=['A', 'B'], index = [1, 2, 3])
df_all = {'df1': A, 'df2': B, 'df3': C}
我想通过索引将它们“内部”合并,但使用 for 循环进行迭代。它必须相当于做
df4 = pd.merge(A, B, left_index=True, right_index=True, how='inner')
df5 = pd.merge(df4, C, left_index=True, right_index=True, how='inner')
结果会是这样的
A_x B_x A_y B_y A B
1 2 1 1 1 1 2
2 2 1 2 2 1 2
3 2 1 3 3 1 2
我尝试了一些类似的傻事
for key, value in df_all.iteritems():
df = pd.merge(value, value, left_index=True, right_index=True, how='inner')
但这给了我一个无意义的结果。
感谢您的帮助。
【问题讨论】:
-
试试
pd.merge(A, A, ...),你就会明白为什么你的结果不起作用了。 -
@chrisaycock 我知道他们为什么不工作。问题是我不知道如何让它们工作。有什么线索吗?
标签: python for-loop dictionary pandas dataframe