2017-08-13 133 views
0

我有一個缺失值的數據框,需要水平插入列。對於插值,某些列的名稱(名稱是數字)將用作插值的索引值。我已經把下面的例子中,以更好地溝通的問題:Python中的線性插值,但使用列標題作爲索引值

初始數據框:

import pandas as pd 
testdata1 = [('Prod', ['P1', 'P2']), 
('A', ['1', '1']), 
('1', ['10', '40']), 
('2', ['', '']), 
('3', ['30', '80']), 
('B', ['1', '2']),    
] 
df = pd.DataFrame.from_items(testdata1) 
df 

Initial df

目標數據框:

targetdf = [('Prod', ['P1', 'P2']), 
('A', ['1', '1']), 
('1', ['10', '40']), 
('2', ['20', '60']), 
('3', ['30', '80']), 
('B', ['1', '2']),    
] 
df2 = pd.DataFrame.from_items(targetdf) 
df2 

Target df

在我的例子上面,要完成的列orm插值(水平)在列'1','2'和'3'上。這些列標題(1,2和3)是插值計算中要使用的索引值。

我知道如何在Python中使用.interpolate(),但只有當索引值是一個特定列中的所有單元格時。任何幫助是極大的讚賞。

回答

1

您可以通過使用行與apply參數axis=1過程:

#replace whitespaces to NaNs 
df = df.replace('', np.nan) 
#rename columns from strings to number 
d = {'1':1,'2':2,'3':3} 
df = df.rename(columns=d) 
#columns for interploate (necessary numeric) 
cols = [1,2,3] 

#convert values in cols to floats first, interpolate and if int output convert to int last 
df[cols] = df[cols].astype(float) 
        .apply(lambda x: x.interpolate(method='index'), axis=1) 
        .astype(int) 
print (df) 
    Prod A 1 2 3 B 
0 P1 1 10 20 30 1 
1 P2 1 40 60 80 2 
+1

謝謝。這工作很棒! – Jdoe

+0

我有一個問題。請問您在哪裏指定了用於插值的索引值?我知道你使用了索引方法,但我無法理解你指定值用於索引的位置。 – Jdoe

+0

它使用列名稱,'1,2,3'。 (f,axis = 1)'和'def f(x):print(x)print(interpolate(method ='index')' – jezrael

0

你提到的列名是數字,但他們列爲您提供的示例數據串。如果它們實際上是數字類型,interpolate()應該只是工作:

import numpy as np 
import pandas as pd 

testdata1 = [('Prod', ['P1', 'P2']), 
      ('A', [1., 1.]), 
      (1, [10., 40.]), 
      (2, [np.nan, np.nan]), 
      (3, [30., 80.]), 
      ('B', [1., 2.]),    
      ] 
df = pd.DataFrame.from_items(testdata1) 

cols = [1,2,3] 
df[cols] = df[cols].interpolate(method="index", axis=1) 

輸出:

Prod A  1  2  3 B 
0 P1 1.0 10.0 20.0 30.0 1.0 
1 P2 1.0 40.0 60.0 80.0 2.0 
+0

嗨安德魯。當我將列名'2'更改爲'2.2'時,我無法讓它工作 – Jdoe

+0

嗨Jdoe ,我剛剛檢查了我的結果,將列從'2'更改爲'2.2'仍然正確執行插值。你能確認你已將'cols'更新爲'[1,2.2,3]'嗎?還有,你能確認該列名實際上是'2.2'而不是字符串表示,即''2.2「'? –

+0

嗨安德魯。由於某種原因,它不適用於我。獲取以下錯誤: TypeError:無法插入所有NaNs – Jdoe

0

轉換爲數字和應用interpolate

In [104]: cols = ['1','2','3'] 

In [105]: df[cols].apply(pd.to_numeric).interpolate(axis=1) 
Out[105]: 
     1  2  3 
0 10.0 20.0 30.0 
1 40.0 60.0 80.0 
+0

嗨,約翰。當我將列名'2'更改爲'2.2'時,我無法實現它的工作。 – Jdoe