【问题标题】:How to define conditional for pandas column of several last row in data frame?如何为数据框中最后几行的熊猫列定义条件?
【发布时间】:2019-07-02 15:47:51
【问题描述】:

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

time                a       b       b           d           e           f 
2018-03-04 10:00:00 86.0    194.0   1.084830    1.088466    196.000000  84.333333
2018-03-04 10:30:00 37.0    59.0    1.082257    1.091397    203.000000  87.833333
2018-03-04 11:00:00 65.0    117.0   1.068825    1.091043    220.166667  96.666667
2018-03-04 11:30:00 10.0    9.0     1.070807    1.087203    183.666667  82.333333
2018-03-04 12:00:00 94.0    157.0   1.083382    1.077549    112.833333  61.666667
2018-03-04 12:30:00 66.0    68.0    1.075636    1.077623    100.666667  59.666667
2018-03-04 13:00:00 224.0   607.0   1.152262    1.088861    169.500000  82.666667
2018-03-04 13:30:00 112.0   279.0   1.119430    1.095057    206.166667  95.166667

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

【问题讨论】:

  • 你的百分比是基于什么的?如果列 f 是 100% 吗?
  • @vlemaistre 100% 将引用数据框中的最后一行,95% 将引用最后第二行等,而不是基于其他列中的其他值。

标签: python pandas


【解决方案1】:

IIUC,g 还没有在df.columns 中,所以我们可以这样做:

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

【讨论】:

  • 抱歉回来了,但你能解释一下:data.iloc[-len(vals):, -1] = vals 是什么意思吗?
【解决方案2】:

看了上面的答案,本来想不发这个的,但不管怎样——

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

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

它给出一个数据框 -

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

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)

这也将为您提供您在问题中要求的内容 -

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 2021-02-28
    • 2013-12-29
    相关资源
    最近更新 更多