簡體   English   中英

通過從其他數據框中提取列來創建新的熊貓數據框-ValueError

[英]Creating new pandas dataframe by extracting columns from other dataframes - ValueError

我必須從不同的熊貓數據框中提取列,並將它們合並到一個新的數據框中。 這就是我在做什么:

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

我確定三列的長度相同(我已經檢查過),但是我得到了錯誤

ValueError: Length of values does not match length of index

我試圖將它們作為pd.Series傳遞,但結果是相同的。 我使用的是Python 2.7。

似乎唯一值的長度存在問題。

一種可能的解決方案是將所有數據連接在一起並應用unique
如果唯一數據的大小不同,請在列的最后一個值中獲取NaN

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

編輯:

另一個可能的解決方案:

a = sorted(df1.columndf1.unique())
b = list(df2.columndf2.unique())
c = list(df3.columndf3.unique())

newdf=pd.DataFrame({'col1':a, 'col2':b, 'col3':c})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM