首页 > 解决方案 > Python 在将函数输出写入同一行中的列的数据帧行上应用函数

问题描述

我有一个如下所示的 DataFrame,我想应用一个函数来计算具有“值”的内容,并根据结果写入其中一列:A、B、C、D 关于哪个结果的信息写入哪一列在字典中

问题是该函数没有将想要的数据写入数据帧。(使用 df.iterrows 它工作但花了很长时间)

  date                flow      A   B   C   D  

0     2017-01-01 00:00:00  7185.0                                  
1     2017-01-01 00:15:00  7145.0                                   
2     2017-01-01 00:30:00  7135.0                                   
3     2017-01-01 00:45:00  7122.0                                  
4     2017-01-01 01:00:00  7142.0   


def my_func(row):
    low, high = nearest_neighbours(row) 

    if row['Flow'] > max(xp):
        col = [k for k, val in dict.iteritems() if value == max(dict.values())]
        row[col] = 0.25

    elif row['Flow'] == 0:
        row['A'] = 0.25

    else:
        col = [k for k, val in dict.iteritems() if value == low]
        row[col] = (high - row['Flow']) / (4 * (high - low))

        col = [k for k, val in dict.iteritems() if value == high]
        row[col] = (row['Flow'] - low) / (4 * (high - low))

df.apply(my_func,axis=1)

从评论中复制:

我有一个看起来像的字典:

{'A':3000, 'B':6000, 'C':9000 etc.} 

我想A-D根据'Flow'值相对于字典的位置在列中写入一些值。
例如:

if Flow ==7500:
    # write some values in C and D

标签: pythonpandasdataframe

解决方案


推荐阅读