首页 > 解决方案 > 如何在公式中使用数据框的某些行

问题描述

因此,我有多个数据框,并且都需要将相同类型的公式应用于此数据框中的某些集合。我得到了 df 中集合的位置,但我不知道如何访问这些集合。这是我的代码:

import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt #might used/need it later to check the output
df = pd.read_csv('Dalfsen.csv')
l = []
x = []
y = []
#the formula(trendline)
def rechtzetten(x,y): 
    a = (len(x)*sum(x*y)- sum(x)*sum(y))/(len(x)*sum(x**2)-sum(x)**2)
    b = (sum(y)-a*sum(x))/len(x)
    y1 = x*a+b
    print(y1)

METING = df.ID.str.contains("<METING>") #locating the sets
indicatie = np.where(METING == False)[0] #and saving them somewhere


if n in df[n] != indicatie & n+1 != indicatie: #attempt to add parts of the set in l
    append.l
elif n in df[n] != indicatie & n+1 == indicatie: #attempt defining the end of the set and using the formula for the set
    append.l
    rechtzetten(l.x, l.y)
else: #emptying the storage for the new set
    l = []

indicatie有以下数字:

 0  12  13  26  27  40  41  53  54  66  67  80  81  94  95 108 109 121
 122 137 138 149 150 162 163 177 178 190 191 204 205 217 218 229 230 242
 243 255 256 268 269 291 292 312 313 340 341 373 374 401 402 410 411 420
 421 430 431 449 450 468 469 487 488 504 505 521 522 538 539 558 559 575
 576 590 591 604 605 619 620 633 634 647

因为我的 df 看起来像这样:

ID,NUM,x,y,nap,abs,end
<PROFIEL>not used data
<METING>data</METING>
<METING>data</METING>
...
<METING>data</METING>
<METING>data</METING>
</PROFIEL>,,,,,,
<PROFIEL>not usde data
...
</PROFIEL>,,,,,,

tl;博士我正在尝试在每个配置文件中使用一个公式,如上所示。我想编辑列表指示的 2 个数字之间的数据。 例如: 函数 rechtzetten(x,y) 用于 x 和 y df.x&df.y[1:11](因为 [0]&[12] 在列表指示中。)然后对于 [14] 也一样: 25]等等等等。我尽量避免的是手动输入以下数百次:

x_#=df.x[1:11]
y_#=df.y[1:11]
rechtzetten(x_#,y_#)

标签: pythonpandasnumpycsv

解决方案


我无法清楚地理解你的问题,但如果你想用一个 numpy 数组替换你的熊猫数据框的特定列,你可以简单地分配它:

df['Column'] = numpy_array

你能更清楚一点吗?


推荐阅读