python - 删除后面没有其他 pd.Series 中的索引的索引

标签 python pandas dataframe

我有两个 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

enter image description here

预期的 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()

enter image description here

关于python - 删除后面没有其他 pd.Series 中的索引的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65113768/

相关文章:

python - 在 setup.cfg 中正确使用 PEP 508 环境标记

python - 无法在 Jupyter 笔记本中下载 nltk.download()

python - 将 stats.percentileofscore 按列应用于每一行

python - 从大文件中剥离 html 比 BeautifulSoup 更快/更少的资源破坏方式?或者,使用 BeautifulSoup 的更好方法?

python - pandas.concat 两个数据框(一个有标题,一个没有标题)

python - 考虑到另一列的值,如何从 DataFrame 中删除重复项

python - 如何从多个 .csv 文件中的命名列中选择唯一值?

python - Pandas - 更改日期列中的每个日期

python - 需要处理具有非唯一多索引的串联数据帧

python - Pandas - 检查某个值是否出现在前一行中