熊猫可以复制数据并与另一个数据框合并吗

时间:2020-03-18 07:16:28

标签: python pandas

我只有一排df1。 df2有多行(我们说8行)

我使用了concat函数来加入这些。 Concat函数将df1放在0索引处,而df2从df1右侧的index1开始。

大熊猫可以重复df1并重复df2并从索引0开始

2 个答案:

答案 0 :(得分:0)

想法由DataFrame.reindex在两个值中创建相同的索引,方法为重复值,然后使用method ='ffill',然后concat,如果不同的第一个索引值正确匹配,也使用DataFrame.set_index

a  c  e
g  i  k
m  o  q
s  u  w
y  1  3
b  d  f
h  j  l
n  p  r
t  v  x
z  2  4

或者如果两个数据帧中的第一个索引值相同:

df1 = pd.DataFrame({
        'A':['s'],
         'B':[50],
         'C':[70]
})


df2 = pd.DataFrame({
        'D':list('abcdef'),
         'E':[4,5,4,5,5,4],
         'F':[7,8,9,4,2,3],

}, index = [10,11,12,13,14,15])

df1 = df1.set_index(df2.index[:len(df1)]).reindex(df2.index, method='ffill')
df = pd.concat([df1, df2], axis=1)
print (df)
    A   B   C  D  E  F
10  s  50  70  a  4  7
11  s  50  70  b  5  8
12  s  50  70  c  4  9
13  s  50  70  d  5  4
14  s  50  70  e  5  2
15  s  50  70  f  4  3

答案 1 :(得分:0)

正如我在评论中所建议的,.join()(或.merge())是执行此操作的理想工具:

# A one-row DataFrame
df1 = pd.DataFrame([[1,2,3,4,5]], columns=list("abcde"))

# A multirow DataFrame
df2 = pd.DataFrame([[1],[2],[3],[4],[5]], columns=("f",))

# A combination
df1.join(df2, how='outer').ffill()
#     a    b    c    d    e  f
# 0  1.0  2.0  3.0  4.0  5.0  1
# 1  1.0  2.0  3.0  4.0  5.0  2
# 2  1.0  2.0  3.0  4.0  5.0  3
# 3  1.0  2.0  3.0  4.0  5.0  4
# 4  1.0  2.0  3.0  4.0  5.0  5

如果需要,可以将浮点数转换回整数。