Pandas join() 有效,但 concat() 失败
Pandas join() works, but concat() fails
我想使用 Pandas 0.14.1.
对具有相同行索引的两个数据帧执行外连接
df1
的形状是456,1
,df2
的形状是139,5
。
df2
中的大多数键都在 df1
中找到:
[in] print len(list(set(df2.index)-set(df1.index)))
[out] 16
join
有效:
[in] df3=df1.join(df2,how='outer')
[in] df3.shape
[out] 473,6
concat
失败:
[in] df3=pd.concat([df1,df2],axis=1,join='outer')
[out] ValueError: Shape of passed values is (6, 473), indices imply (6, 472)
这可能是什么原因造成的?
如果其中一个索引具有重复值,您可能会收到此错误。例如,
import pandas as pd
df1 = pd.DataFrame(np.random.random((5,1)), index=list('AACDE'),
columns=['foo'])
df2 = pd.DataFrame(np.random.random((4,1)), index=list('CDEF'),
columns=['bar'])
然后
In [50]: df1.join(df2, how='outer')
Out[50]:
foo bar
A 0.846814 NaN
A 0.638571 NaN
C 0.516051 0.573165
D 0.789398 0.095466
E 0.921592 0.970619
F NaN 0.061434
但是
In [51]: pd.concat([df1,df2], axis=1, join='outer')
ValueError: Shape of passed values is (2, 6), indices imply (2, 5)
我想使用 Pandas 0.14.1.
对具有相同行索引的两个数据帧执行外连接df1
的形状是456,1
,df2
的形状是139,5
。
df2
中的大多数键都在 df1
中找到:
[in] print len(list(set(df2.index)-set(df1.index)))
[out] 16
join
有效:
[in] df3=df1.join(df2,how='outer')
[in] df3.shape
[out] 473,6
concat
失败:
[in] df3=pd.concat([df1,df2],axis=1,join='outer')
[out] ValueError: Shape of passed values is (6, 473), indices imply (6, 472)
这可能是什么原因造成的?
如果其中一个索引具有重复值,您可能会收到此错误。例如,
import pandas as pd
df1 = pd.DataFrame(np.random.random((5,1)), index=list('AACDE'),
columns=['foo'])
df2 = pd.DataFrame(np.random.random((4,1)), index=list('CDEF'),
columns=['bar'])
然后
In [50]: df1.join(df2, how='outer')
Out[50]:
foo bar
A 0.846814 NaN
A 0.638571 NaN
C 0.516051 0.573165
D 0.789398 0.095466
E 0.921592 0.970619
F NaN 0.061434
但是
In [51]: pd.concat([df1,df2], axis=1, join='outer')
ValueError: Shape of passed values is (2, 6), indices imply (2, 5)