簡體   English   中英

使用整數列表/元組替換Pandas DataFrame列中的值

[英]Replace values in Pandas DataFrame column with integer lists / tuples

我想將包含國際象棋方形坐標的3列pandas數據幀df替換為字符串,使用字典chess_dict以2x1整數列表的形式將它們映射到笛卡爾坐標。

我已經嘗試過使用replace方法,但由於某種原因它只替換了列表的第一個整數,而不是兩者

例如。 ('a1','h6') - >([0,0],[7,5])

>>>chess_dict
 {'a1': [0, 0],
 'a2': [0, 1],
 ...
 'h5': [7, 4],
 'h6': [7, 5],
 'h7': [7, 6],
 'h8': [7, 7]}

>>>df
      WK  WR  BK plays outcome
0     h4  e6  a4     b       w
1     a6  h4  g8     w       w
2     f5  a3  d1     w       w
3     c2  h3  f5     w       w
...
>>>df.ix[:,0].replace(chess_dict, inplace=True)
>>>df.ix[:,1].replace(chess_dict, inplace=True)
>>>df.ix[:,2].replace(chess_dict, inplace=True)
>>>df
      WK  WR  BK plays outcome
0      7   4   0     b       w
1      5   3   7     w       w
2      5   0   3     w       w
3      1   2   4     w       w
...
  • 我已經嘗試用笛卡爾坐標作為字符串替換,然后將字符串轉換為整數列表並且它有效,但是因為我是python和pandas的新手我猜測有一種更簡單的方法使用替換但是有一些基本的我失蹤了,我似乎無法弄明白。

  • 我也嘗試了這種語法,結果相同:

     df.ix[:,0].replace(to_replace = chess_dict.keys(), value = chess_dict.values(), inplace=True) 
  • 我也嘗試使用整數元組作為笛卡爾坐標(0,0),(0,1)等,但現在只在DataFrame列中插入了最后一個而不是第一個值

     WK WR BK plays outcome 0 3 g7 b4 bw 1 3 h7 d1 bw 2 3 h6 f5 ww 3 6 d5 b1 bw 

選項1

chess_dict = {
    r + c: [i, j]
        for i, r in enumerate(list('abcdefgh'))
        for j, c in enumerate(list('12345678'))
}

df.iloc[:, :3].stack().map(chess_dict).unstack().join(df.iloc[:, 3:])

       WK      WR      BK plays outcome
0  [7, 3]  [4, 5]  [0, 3]     b       w
1  [0, 5]  [7, 3]  [6, 7]     w       w
2  [5, 4]  [0, 2]  [3, 0]     w       w
3  [2, 1]  [7, 2]  [5, 4]     w       w

選項2

df.applymap(lambda x: chess_dict.get(x, x))

       WK      WR      BK plays outcome
0  [7, 3]  [4, 5]  [0, 3]     b       w
1  [0, 5]  [7, 3]  [6, 7]     w       w
2  [5, 4]  [0, 2]  [3, 0]     w       w
3  [2, 1]  [7, 2]  [5, 4]     w       w

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM