我有两个 Pandas 系列,我想过滤掉索引后面没有其他系列索引的数据。因此,在加入这些系列时,基于索引,只有所有其他数据点都应该来自data1
,反之亦然。
代码:
import pandas as pd
import matplotlib.pyplot as plt
data1={1:20, 3:30, 5:40, 6:50}
data2={2:10, 4:20, 7:30, 9:40}
data1=pd.Series(data1)
data2=pd.Series(data2)
print(data1)
print(data2)
ax=plt.subplot()
ax.plot(data1,marker='o')
ax.plot(data2,marker='o')
plt.show()
输出:
(箭头显示我想要过滤掉的数据点)
1 20
3 30
5 40
6 50
dtype: int64
2 10
4 20
7 30
9 40
dtype: int64
预期的 pandas 函数可以解决我的问题:
expectedData1=data1[data1.index.isNotFollowedBy(data2.index)]
expectedData2=data2[data2.index.isNotFollowedBy(data1.index)]
该函数的预期输出:
1 20
3 30
6 50
dtype: int64
2 10
4 20
9 40
dtype: int64
最佳答案
您可以将两个系列连接到一个数据框中,并使用 shift()
根据您的评论对它们进行比较,并过滤掉这些行。
df = data1.reset_index().join(data2.reset_index(), rsuffix='_y')
df = df[(df['index'].shift(-1) > df['index_y']) | (df['index'] == df['index'].iloc[-1])]
data1 = df.iloc[:,0:2].set_index('index').iloc[:,0]
data2 = df.iloc[:,2:].set_index('index_y').iloc[:,0]
然后,您可以绘制:
ax=plt.subplot()
ax.plot(data1,marker='o')
ax.plot(data2,marker='o')
plt.show()
关于python - 删除后面没有其他 pd.Series 中的索引的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65113768/