如何交换不同列表和不同大小 Pandas 中的元素?

How to swap elements in different list and different size Pandas?

我有一个数据框 df1。数据框有一列名为 'Path'。每行都有一个列表。他们是这样的:

Path                   
____________________
[OAK, PHX, MIA, FLL, PBG]   
[OAK, SEA, FLL, PBG]   
[OAK, LAS, ORD, FLL, PBG]   
[OAK, DFW, FLL, PBG]
...

我希望将每个奇数行的 secondthird 值与对应的 second[=28 交换=] 和 third 下一行(偶数行)的值,然后分别交换每一对。在上面的输入示例中,第一行的值 PHX, MIA 应与第二行的值 SEA, FLL 交换,然后取反。

Path                   
____________________
[OAK, PHX, MIA, FLL, PBG]   
[OAK, SEA, FLL, PBG]   

# Swap 2nd and 3rd value between rows 

Path                   
____________________
[OAK, SEA, FLL, FLL, PBG]   
[OAK, PHX, MIA, PBG]

# Swap 2nd and 3rd value in all rows
Path                   
____________________
[OAK, FLL, SEA, FLL, PBG]   
[OAK, MIA, PHX, PBG]

结果应该是这样的:

Path                   
____________________
[OAK, FLL, SEA, FLL, PBG]   
[OAK, MIA, PHX, PBG]   
[OAK, FLL, DFW, FLL, PBG]   
[OAK, ORD, LAS, PBG]
.... 

如何使用 Python 完成?

out = df['Path'].apply(lambda x : pd.Series(x)  )

dfLength = len(df)
if dfLength%2==0:
    oddIndex = list(range(0,dfLength-1, 2))
    evenIndex = list(range(1, dfLength,2))
else:
    oddIndex = list(range(0,dfLength, 2))
    evenIndex = list(range(1, dfLength,2))

#Swapping odd-even rows
oddData = out.iloc[oddIndex][[1,2]].copy() 
evenData = out.iloc[evenIndex][[1,2]].copy()

out.iloc[oddIndex, [1,2]] = evenData.values
out.iloc[evenIndex, [1,2]] = oddData.values

#Swapping columns 2 & 3
col2 = out.loc[:,1].copy()
col3 = out.loc[:,2].copy()

out.loc[:,1] = col3.values
out.loc[:,2] = col2.values

最终输出看起来像

     0    1    2    3    4
0  OAK  FLL  SEA  FLL  PBG
1  OAK  MIA  PHX  PBG  NaN
2  OAK  FLL  DFW  FLL  PBG
3  OAK  ORD  LAS  PBG  NaN

如果您希望输出为列表,

out.apply(lambda x : list(x.dropna().values), axis = 1)
0    [OAK, PHX, MIA, FLL, PBG]
1         [OAK, SEA, FLL, PBG]
2    [OAK, LAS, ORD, FLL, PBG]
3         [OAK, DFW, FLL, PBG]
4         [OAK, DFW, FLL, PBG]