Python Pandas,删除列的增加行

时间:2018-04-19 22:27:08

标签: python pandas matplotlib rows

以下是我的问题的简短示例版本:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


x = np.arange(1, 101, 1)
y1 = np.linspace(0, 1000, 50)
y2 = np.linspace(500, 2000, 50)
y = np.concatenate((y1, y2))
data = np.asmatrix([x, y]).T
df = pd.DataFrame(data)

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(df.iloc[:, 0], df.iloc[:, 1], 'r')
plt.gca().invert_yaxis()
plt.show()

请运行代码并查看其生成的图表。enter image description here

我想从后面读取数据帧(从x = 100到x = 0)并确保我的y轴总是在减小(从y = 2000到y = 0)。我想删除从数据帧末尾读取时y值没有减少的行。

如何编辑我的数据框以实现此目的?

1 个答案:

答案 0 :(得分:1)

我对这个解决方案并不满意,但总比没有好。我发现很难描述这个问题而不会变得太模糊。如果你看到改进的余地,请评论,因为我知道有。

newindex = []
max = -999

for row in df.index:
    if df.loc[row, 1] > max:
        max = df.loc[row, 1]
        newindex.append(row)

df = df.loc[newindex,]