我有一个缺少值的dataframe,我需要在列之间水平插值。对于插值,某些列的名称(名称为数字)将用作插值的索引值。为了更好地沟通这个问题,我整理了以下示例:
初始数据帧:
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

目标数据帧:
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

在上面的例子中,要(水平地)执行插值的列是列“1”、“2”和“3”。并且那些列标题(1、2和3)是在插值计算中使用的索引值。
我知道如何在Python语言中使用.interpolate(),但只有当索引值都是某个特定列中的单元格时才能使用。任何帮助都是非常感谢的。
发布于 2017-08-14 01:33:03
对于按行处理,可以使用带有参数axis=1的apply:
#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发布于 2017-08-14 01:41:30
您提到列名是数字的,但是它们在您提供的示例数据中是作为字符串列出的。如果它们实际上是数值类型,那么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发布于 2017-08-14 01:42:27
转换为数字并应用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.0https://stackoverflow.com/questions/45660907
复制相似问题