通过从其他dataframes值提取列来创建新的pandas dataframe

2024-10-03 09:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须从不同的pandas数据帧中提取列,并将它们合并到一个新的数据帧中。这就是我要做的:

newdf=pd.DataFrame()
newdf['col1']=sorted(df1.columndf1.unique())
newdf['col2']=df2.columndf2.unique(),
newdf['col3']=df3.columndf3.unique()
newdf

我确信这三列的长度相同(我已经检查过了),但是我得到了错误

^{pr2}$

我试着把它们当作pd系列但结果是一样的。我使用的是python2.7。在


Tags: 数据dataframepandascol2col3col1pdunique
1条回答
网友
1楼 · 发布于 2024-10-03 09:09:58

似乎有问题唯一值的长度不同。在

一种可能的解决方案是将所有数据合并在一起并应用unique
如果唯一数据的大小不同,则在列的最后一个值中获取NaNs。在

newdf = pd.concat([df1.columndf1, df2.columndf2, df3.columndf3], axis=1)
          .apply(lambda x: pd.Series(x.unique()))

编辑:

另一个可能的解决方案:

^{pr2}$

相关问题 更多 >