簡體   English   中英

在python pandas中,如何重新采樣和插入DataFrame?

[英]In python pandas, how can I re-sample and interpolate a DataFrame?

我有一個pd DataFrame,通常采用以下格式:

   1       2          3          4  
0.1100 0.0000E+00 1.0000E+00 5.0000E+00  
0.1323 7.7444E-05 8.7935E-01 1.0452E+00  
0.1545 4.3548E-04 7.7209E-01 4.5432E-01  
0.1768 1.2130E-03 6.7193E-01 2.6896E-01  
0.1990 2.5349E-03 5.7904E-01 1.8439E-01  
0.2213 4.5260E-03 4.9407E-01 1.3771E-01 

我想要做的是從列表中重新采樣列1(索引)值,例如:

indexList = numpy.linspace(0.11, 0.25, 8)

然后我需要從輸入DataFrame線性插值第2,3和4列的值(它總是只有我重新采樣/重新索引的第1列) - 如果需要外推,作為我的最小值/最大值list不一定在我現有的第1列(索引)中。 然而,關鍵點是插值部分。 我是python的新手,但我正在考慮使用這樣的方法:

  1. output_df = DataFrame.reindex(index = indexList) - 這將主要給出第2-4列的NaN。
  2. for index,output_df.iterrows()中的行
    “從DataFrame計算插值/外推值並將其插入正確的行/列的函數”

不知何故感覺我應該能夠使用.interpolate功能,但我無法弄清楚如何。 我不能直接使用它 - 它太不准確,因為在第2-4列中提到的重新索引后的大多數條目都是NaN的; 插值應該在我的初始DataFrame的兩個最接近的值內完成。 任何好的提示有人嗎? (如果我的格式/意圖不清楚,請告訴我......)

假設列1在索引中,您可以使用原始值和您創建的列表重新索引數據幀,然后使用interpolate填充nan。

df1 = df.reindex(df.index.union(np.linspace(.11,.25,8)))
df1.interpolate('index')

               2         3         4
0.1100  0.000000  1.000000  5.000000
0.1300  0.000069  0.891794  1.453094
0.1323  0.000077  0.879350  1.045200
0.1500  0.000363  0.793832  0.574093
0.1545  0.000435  0.772090  0.454320
0.1700  0.000976  0.702472  0.325482
0.1768  0.001213  0.671930  0.268960
0.1900  0.001999  0.616698  0.218675
0.1990  0.002535  0.579040  0.184390
0.2100  0.003517  0.537127  0.161364
0.2213  0.004526  0.494070  0.137710
0.2300  0.004526  0.494070  0.137710
0.2500  0.004526  0.494070  0.137710

在我們開始一些法術之前:

import pandas as pd
import numpy

LENGTH=8

讓我們從加載數據開始(我們將更改為csv,因為它更容易):

x="""   1       2          3          4
0.1100 0.0000E+00 1.0000E+00 5.0000E+00
0.1323 7.7444E-05 8.7935E-01 1.0452E+00
0.1545 4.3548E-04 7.7209E-01 4.5432E-01
0.1768 1.2130E-03 6.7193E-01 2.6896E-01
0.1990 2.5349E-03 5.7904E-01 1.8439E-01
0.2213 4.5260E-03 4.9407E-01 1.3771E-01
"""
nx = ""
for l in x.split('\n'):
    nx += ','.join(l.split()) + '\n'
df= pd.read_csv(pd.compat.StringIO(nx))

現在,您希望在相同數據上插入一個新數據幀,但是數組的值介於0.11和0.25之間:

indexList = numpy.linspace(0.11, 0.25, LENGTH)

我們將使用第一列作為索引,並使用reindex:

df_interpolated = df.reindex(df.index.union(indexList)).interpolate('index')
df_interpolated.head(LENGTH)

             1         2         3         4
0.00  0.110000  0.000000  1.000000  5.000000
0.11  0.112453  0.000009  0.986729  4.564972
0.13  0.112899  0.000010  0.984316  4.485876
0.15  0.113345  0.000012  0.981903  4.406780
0.17  0.113791  0.000013  0.979490  4.327684
0.19  0.114237  0.000015  0.977077  4.248588
0.21  0.114683  0.000016  0.974664  4.169492
0.23  0.115129  0.000018  0.972251  4.090396
0.25  0.115575  0.000019  0.969838  4.011300

暫無
暫無

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

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