尝试从列表中选择子集,但选择后顺序会颠倒
尝试使用 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 为止。
流程
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/