【问题标题】:merge two dataframes by row with same index pandas用相同的索引熊猫按行合并两个数据帧
【发布时间】:2016-09-06 16:44:53
【问题描述】:

假设我有以下两个数据帧 X1 和 X2。我想 按行合并这两个数据帧,以便每个索引 相同的数据框结合了两者的相应行 数据框。

       A  B C  D
DATE1 a1 b1 c1 d1

DATE2 a2 b2 c2 d2

DATE3 a3 b3 c3 d3


       A B  C  D
DATE1 f1 g1 h1 i1

DATE2 f2 g2 h2 i2

DATE3 f3 g3 h3 i3

how would i combine them to get


      A  B  C  D
DATE1 A1 B1 C1 D1
      f1 g1 h1 i1

DATE2 A2 B2 C2 D2
      f2 g2 h2 i2

DATE3 A3 B3 C3 D3
      f3 g3 h3 i3

到目前为止我已经尝试过了,但这似乎不起作用:

 d= pd.concat( { idx : [ X1[idx], X2[idx]]  for idx, value in appended_data1.iterrows() } , axis =1}

谢谢

【问题讨论】:

  • 你想把这两行合并成什么?具有相同日期、列表或字典的两个单独的行?
  • 是两个不同的行,日期相同

标签: python pandas dataframe append concatenation


【解决方案1】:

选项 1

df3 = df1.stack().to_frame('df1')
df3.loc[:, 'df2'] = df2.stack().values
df3 = df3.stack().unstack(1)
df3


选项 2 广义的

idx = df1.stack().index

dfs = [df1, df2]
dflabels = ['df1', 'df2']

a = np.stack([d.values.flatten() for d in dfs], axis=1)
df3 = pd.DataFrame(a, index=idx, columns=dflabels).stack().unstack(1)

设置

from StringIO import StringIO
import pandas as pd


df1_text = """       A  B C  D
DATE1 a1 b1 c1 d1
DATE2 a2 b2 c2 d2
DATE3 a3 b3 c3 d3"""


df2_text = """       F  G H  I
DATE1 f1 g1 h1 i1
DATE2 f2 g2 h2 i2
DATE3 f3 g3 h3 i3"""

df1 = pd.read_csv(StringIO(df1_text), delim_whitespace=True)
df2 = pd.read_csv(StringIO(df2_text), delim_whitespace=True)

df1

df2

【讨论】:

  • 漂亮!谢谢你!! srry 试过但不能投票,因为排名不够高 - 希望其他人会
  • 我想知道如果我想迭代这个过程并添加更多的数据帧我会怎么做?谢谢
  • 没关系。我想我可以添加第二行并遍历数据帧名称列表。它有效。刚刚尝试过
  • @PythonTitus 我用一个比迭代更好的通用解决方案更新了帖子。
【解决方案2】:

也许这个解决方案也可以解决您的问题:

df3 =  pd.concat([df1,df2]).sort_index()

print df3
Out[42]: 
         A   B   C   D
DATE1  a1  b1  c1  d1
DATE1  f1  g1  h1  i1
DATE2  a2  b2  c2  d2
DATE2  f2  g2  h2  i2
DATE3  a3  b3  c3  d3
DATE3  f3  g3  h3  i3

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 2018-07-17
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多