使用pandas.DataFrame.interpolate将行添加到DataFrame [英] Using pandas.DataFrame.interpolate to add rows to DataFrame

查看:100
本文介绍了使用pandas.DataFrame.interpolate将行添加到DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Pandas数据框,格式如下:

I have a Pandas dataframe with the following format:

    Frequency | Value
1   10          2.8
2   20          2.5
3   30          2.2
4   40          2.3

我想使用pandas.DataFrame.interpolate来添加频率为35的线,并在频率30和40之间线性插值.

I want to use pandas.DataFrame.interpolate in order to add a line at frequency 35 with a value interpolated linearly between frequencies 30 and 40.

该示例在用户手册中显示了如何替换Nan而不是如何在其他之间添加值(

In the user manual the example shows how to replace a Nan but not how to add values in between others (Pandas doc).

最好的进行方式是什么?

What would be the best way to proceed ?

推荐答案

我认为您需要先通过35添加到frequency列中-docs/stable/generated/pandas.DataFrame.loc.html"rel =" noreferrer> loc

I think you need first add new value 35 to frequency column by loc, sort_values and then interpolate:

df.loc[-1, 'Frequency'] = 35
df = df.sort_values('Frequency').reset_index(drop=True)
print (df)
   Frequency  Value
0       10.0    2.8
1       20.0    2.5
2       30.0    2.2
3       35.0    NaN
4       40.0    2.3

df = df.interpolate()
print (df)
   Frequency  Value
0       10.0   2.80
1       20.0   2.50
2       30.0   2.20
3       35.0   2.25
4       40.0   2.30

使用Series的解决方案,谢谢您的想法罗格·卡西斯(Rutger Kassies).

Solution with Series, thank you for idea Rutger Kassies.

DataFrame.squeeze 创建包含一栏DataFrame.

s = df.set_index('Frequency').squeeze()
s.loc[35] = np.nan
s = s.sort_index().interpolate(method='index')
print (s)
Frequency
10    2.80
20    2.50
30    2.20
35    2.25
40    2.30
Name: Value, dtype: float64

这篇关于使用pandas.DataFrame.interpolate将行添加到DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆