python - 从列表中选择数据,同时保持顺序

标签 python pandas numpy python-xarray

尝试从列表中选择子集,但选择后顺序会颠倒

尝试使用 pandas isin

df.mon =[1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12,...] 
 # selecting 
 results = df[df.month.isin([10,11,12,1,2,3])]
 print(results.mon]
 mon = [1,2,3,10,11,12, 1,2,3,10,11,12,...]
 desired results
 mon= [10,11,12,1,2,3,10,11,12,1,2,3,...]

 # sorting results in this
 mon = [1,1,2,2,3,3,10,10,11,11,12,12] and I dont want that either

 thanks for the help

最佳答案

我主要使用基本的 python 列表,因此我已将 df 转换为列表。

数据

数据显示在这样的 xlsx 文件中。 输入是一个 xlsx 文档,其中 1, 2, .. 12, 1, 2, .. 12 仅出现两次,“值”从 90 开始,一直到第二个 12 为止。

A portion of the xlsx file

流程

import pandas as pd

df = pd.read_excel('Book1.xlsx')
arr = df['Column'].tolist()
arr2 = df['Values'].tolist()

monthsofint = [10, 11, 12, 1, 2, 3]

locs = []

dictor = {}
for i in range(len(monthsofint)):
    dictor[monthsofint[i]] = []

for i in range(len(monthsofint)):  # !! Assumption !!
    for j in range(len(arr)):
        if monthsofint[i] == arr[j]:
            dictor[monthsofint[i]].append(j)

newlist = []
newlist2 = []
for i in range(len(dictor[monthsofint[0]])):
    for j in range(len(monthsofint)):
        newlist.append(arr[dictor[monthsofint[j]][i]])
        newlist2.append(arr2[dictor[monthsofint[j]][i]])

print(newlist)
print(newlist2)

输出:[10, 11, 12, 1, 2, 3, 10, 11, 12, 1, 2, 3][180, 190, 200, 90, 100、110、300、310、320、210、220、230]

关于假设的说明:所做的假设是文件中每年始终有 12 个月。

关于python - 从列表中选择数据,同时保持顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024183/

相关文章:

python - Pandas 不为空,但获取max()arg为空序列

python - 描述时间序列 Pandas 中的差距

python - 在Anaconda中播放文件中的视频

python - python多处理中池的用途

python - Pandas 如何使用 pd.cut()

python - 稀疏矩阵上 hstack 的类型错误

python - IPython notebook 中 pretty-print 多项式

python - 如何安装pybrain?

python - 将函数链接为 python 中的 shell 管道命令

python - 从最后可用数据创建 DataFrame 的最快方法