如何为数据帧中最后几行的熊猫列定义条件?

时间:2019-07-02 15:47:51

标签: python pandas

假设我有一个数据框,其中这些行是最后8行。

inches = input "How many inches?"
cm = inches*2.54
print "That is" {} "centimeters.".format(cm)

如何使用此条件在Pandas上创建新列“ g”: 如果该行是最后一行,则值为100%, 如果该行是最后第二行,则值为95%..直到达到70%,否则它将为0?

2 个答案:

答案 0 :(得分:5)

IIUC,g尚未在df.columns中,所以我们可以这样做:

vals = np.arange(0.7,1,0.05)
df['g'] = 0
df.iloc[-len(vals):, -1] = vals

答案 1 :(得分:1)

看着上面的答案,我想到了不发布此内容,但是无论如何-

假设您创建了一个数据框-

data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy','Jason', 'Molly', 'Tina', 'Jake', 'Amy','Jason', 'Molly', 'Tina', 'Jake', 'Amy','Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
        'age': [42, 52, 36, 24, 73, 42, 52, 36, 24, 73, 42, 52, 36, 24, 73, 42, 52, 36, 24, 73], 
        'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 4, 24, 31, 2, 3],
df = pd.DataFrame(data, columns = ['name', 'age', 'preTestScore', 'postTestScore'])
df

它给出一个数据框-

dataframe

现在创建一个新列表,可以将其添加为我们数据框中的新列-

indexList = df.index.tolist()

listToBeInsertedInNewColumn = []

newElement = 100
i = len(indexList)-1
listToBeInsertedInNewColumn.append(str(newElement)+"%")
while i >= 1:
    newElement -= 5
    if newElement >= 70:
        listToBeInsertedInNewColumn.append(str(newElement)+"%")
    else:
        listToBeInsertedInNewColumn.append("0%")
    i -= 1

listToBeInsertedInNewColumn.reverse()

最后将其添加到数据框-

df['g'] = list(listToBeInsertedInNewColumn)

这还将为您提供问题中的要求-

New Dataframe

它不像原始答案那么干净,但是仍然是答案。