【问题标题】:pandas for loop interpolate循环插值的熊猫
【发布时间】:2019-07-27 13:34:01
【问题描述】:

我正在尝试为 218 个国家/地区的 7 个指标插入数据。我的 for 循环可以工作,但在将结果导出到 .csv 时遇到问题。目前,我的“插值”数据框仅包含最后一个国家/地区的插值数据。

for i in df['Country']:
   country_interp= df[df['Country'] == i]
   upsampled = country_interp.resample('YS') 
   interpolated=upsampled.interpolate(method='linear', limit_area='inside')


Year         Country  Equiped_Actually_Irr    ...     Equiped_Ai        Ai
1992-01-01  Zimbabwe                   NaN    ...            NaN  0.056710
1993-01-01  Zimbabwe                   NaN    ...            NaN  0.056304
1994-01-01  Zimbabwe                   NaN    ...            NaN  0.055898
1995-01-01  Zimbabwe                   NaN    ...            NaN  0.055492
1996-01-01  Zimbabwe                   NaN    ...            NaN  0.055085
1997-01-01  Zimbabwe                   NaN    ...            NaN  0.054679
1998-01-01  Zimbabwe                   NaN    ...            NaN  0.054273

【问题讨论】:

    标签: pandas loops csv interpolation


    【解决方案1】:

    您应该在循环外创建一个数据帧,然后将新生成的数据帧附加/连接到外部。

    试试:

    interpolate = pd.DataFrame()
    for i in df['Country']:
       country_interp= df[df['Country'] == i]
       upsampled = country_interp.resample('YS') 
       interpolated=upsampled.interpolate(method='linear', limit_area='inside')
       interpolate = pd.concat(['interpolate', 'interpolated'], 0 , sort = False)
    

    您可能会收到与排序相关的错误/警告。如果是这种情况,您可以添加 columns = [] 在 pd.DataFrame() 中

    【讨论】:

    • 运行代码时出现以下错误:TypeError: cannot concatenate object of type "";只有 pd.Series、pd.DataFrame 和 pd.Panel(已弃用)obj 是有效的。
    • 你确定 interpolated 是一个数据范围吗?
    • 是的,它将其列为数据框
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2023-03-17
    相关资源
    最近更新 更多