简体   繁体   English

使用整数列表/元组替换Pandas DataFrame列中的值

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

I want to replace 3 columns of a pandas dataframe df containing chess square coordinates as strings, using a dictionary chess_dict to map them to Cartesian coordinates in the form of 2x1 integer lists. 我想将包含国际象棋方形坐标的3列pandas数据帧df替换为字符串,使用字典chess_dict以2x1整数列表的形式将它们映射到笛卡尔坐标。

I've tried using the replace method, but for some reason it replaces with the first integer of the list only, instead of both 我已经尝试过使用replace方法,但由于某种原因它只替换了列表的第一个整数,而不是两者

eg. 例如。 ('a1','h6') -> ([0,0],[7,5]) ('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
...
  • I have tried replacing with the Cartesian coords as strings, and afterwards converting the string to integer lists and it worked, but since I'm new to python and pandas I'm guessing there is a simpler way using replace but there is something basic I'm missing which I just can't seem to figure out. 我已经尝试用笛卡尔坐标作为字符串替换,然后将字符串转换为整数列表并且它有效,但是因为我是python和pandas的新手我猜测有一种更简单的方法使用替换但是有一些基本的我失踪了,我似乎无法弄明白。

  • I've also tried this syntax with the same results: 我也尝试了这种语法,结果相同:

     df.ix[:,0].replace(to_replace = chess_dict.keys(), value = chess_dict.values(), inplace=True) 
  • I've also tried using integer tuples for the Cartesian coords (0,0), (0,1), etc., but now only the last instead of first value is inserted in the DataFrame column 我也尝试使用整数元组作为笛卡尔坐标(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 

option 1 选项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

option 2 选项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