我想创建一个列,它根据同一行中值之间的if语句创建一个值,如果需要,还可以在上面的行中创建一个值。我有一个恒定的A和df
A = 0.5
FID_1 b c d e
75907 nan 33021647.00 27014.12 27014.12 1.00
75858 159510.00 32888862.00 16532.64 28797.05 0.57
75859 159510.00 32888862.00 12264.41 28797.05 0.43
75795 nan 32869718.00 24218.16 24218.16 1.00
75518 nan 32574894.00 13304.45 13304.45 1.00
我想创建另一个名为f
的列,该列将告诉我e
中的值是否大于A或b
中给定值的值。如果这是正确的,则值为1。
以上df的示例:
FID_1 b c d e f
75907 nan 33021647.00 27014.12 27014.12 1.00 1
75858 159510.00 32888862.00 16532.64 28797.05 0.57 1
75859 159510.00 32888862.00 12264.41 28797.05 0.43 0
75795 nan 32869718.00 24218.16 24218.16 1.00 1
75518 nan 32574894.00 13304.45 13304.45 1.00 1
更棘手的是,如果我将A
的值更改为0.6
。在这种情况下,我想看看b
中的每个数字,如果b
中第一行的值在e
中的值大于A
,如果没有,我想看到第二行相同的sum
值e
中的值df
并检查它是否大于A.与A=0.6
的 FID_1 b c d e f
75907 nan 33021647.00 27014.12 27014.12 1.00 1
75858 159510.00 32888862.00 16532.64 28797.05 0.57 0
75859 159510.00 32888862.00 12264.41 28797.05 0.43 1
75795 nan 32869718.00 24218.16 24218.16 1.00 1
75518 nan 32574894.00 13304.45 13304.45 1.00 1
如下所示:
b
在这种情况下,代码在df的第三行中求和0.57和0.43。
如果情况不是这样的话,那么代码会在e
中寻找相同值的第三,第四,......行 - 如果它存在的话。
这是用于创建df['e'] = df.apply(lambda row: row.c / row.d, axis=1)
列的代码
f
我尝试类似于if statement
列,但我不知道如何在相同的代码中输入def STAcondition (row):
if row['e'] > A :
return 0
if row['e'] < A :
return 1
return 'Other'
df['f'] = df.apply (lambda row: STAcondition (row),axis=1)
。
这是我的解决方案的开始:
import pandas as pd
import numpy.random as npr
import numpy as np
# Dummy data
dfInit = {
'FID_1':npr.randint(0,10,10),
'b':npr.randint(0,10,10),
'c':npr.randint(0,10,10),
'd':npr.randint(0,10,10),
'e':npr.randint(0,10,10)
}
dfIndex = np.arange(0,10)
df = pd.DataFrame(data=dfInit, index=dfIndex)
# Algo
df['f'] = np.zeros(10)
A = 6
def letsMakeAnF(value):
# check if value is in b
if value in df['b'].unique():
occurrenceMatch = df.loc[df['b'] == value,:]
else:
print('value not in b series')
return
if occurrenceMatch['e'].iloc[0] > A:
df['f'].ix[occurrenceMatch.index[0]] == 1
else:
if np.sum(occurrenceMatch['b']) > A:
df['f'].ix[occurrenceMatch.index[-1]] = 1
#Generate random 'wanted' values
values = [npr.randint(0, 10) for x in range(10)]
#Iterate over the values and modify the DF. Note that in this case
#df is a global variable
for value in values:
letsMakeAnF(value)
也许尝试在多个步骤中创建f。如果我理解正确,你的伪算法应如下所示:
这是我画的东西:
qazxswpoi
希望能帮助到你!