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

标签 python pandas dataframe

我想将包含国际象棋方格坐标的 pandas 数据框 df 的 3 列替换为字符串,使用字典 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 的新手,我猜有一种更简单的方法使用 < strong>replace 但我缺少一些基本的东西,我似乎无法弄清楚。

  • 我也尝试过这种语法并得到相同的结果:

    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     b       w
    1      3  h7  d1     b       w
    2      3  h6  f5     w       w
    3      6  d5  b1     b       w
    

最佳答案

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

关于python - 用整数列表/元组替换 Pandas DataFrame 列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43451514/

相关文章:

r - 如何用R中的查找代码用字符串替换列

python - 使用python访问函数内部的字典

python - 使用 "long-data"数据格式合并数据透视表

python - dataframe iloc 在 pandas 中出乎意料地工作

python - 如何在 Pandas 系列中找到与特定值匹配的最后一次出现索引?

python - 在多索引数据框中定位特定数据

python - 检查实体中是否存在某个字段

python - 在实时视频中统计人数

python - 如何产生 "Callable function"

python - 如何使用生成器避免 python 中的最大递归深度?