【问题标题】:Replace a cell's value in pandas to a tuple将 pandas 中单元格的值替换为元组
【发布时间】:2021-01-18 18:24:47
【问题描述】:

这可能是一个简单的问题,但我尝试寻找答案,但似乎找不到。 我有一个 pandas 数据框,我想将一些单元格的值更改为一个元组。

如果我有这个:

 Col0    Col1     Col2
   3      a        6
   7      b        8

我想将所有“a”值更改为一个元组:

Col0      Col1     Col2
3         (4,5)      6
7          b         8

我试过这样做:

df.loc[df["Col1"] == "a"] = (4,5,)

但它显然没有用。我不知道我该怎么做。

我该怎么做?

【问题讨论】:

    标签: python pandas string tuples


    【解决方案1】:

    让我们尝试使用loc 进行布尔索引来更新Col1 中包含a 的单元格中的值:

    m = df['Col1'].eq('a')
    df.loc[m, 'Col1'] = pd.Series([(4, 5)]*m.sum(), index=m[m].index)
    

    或者,您可以尝试 .reindexfill_value 参数设置为元组 (4, 5)

    m = df['Col1'].eq('a')
    df['Col1'] = df.loc[~m, 'Col1'].reindex(m.index, fill_value=(4, 5))
    

       Col0    Col1  Col2
    0     3  (4, 5)     6
    1     7       b     8
    

    【讨论】:

      【解决方案2】:

      也许是这样的?

      import pandas as pd
      df = pd.DataFrame(data = {'Col0': [3,7], 'Col1': ['a', 'b'], 'Col2': [6, 8]})
      df.set_value(0, 'Col1', (4, 5))
      

      或者,如果您不知道 'a' 在哪里(如果我们每列有多个 'a0,您可以通过循环来做到这一点:

      import pandas as pd
      import numpy as np
      
      df = pd.DataFrame(data = {'Col0': [3,7], 'Col1': ['a', 'b'], 'Col2': [6, 8]})
      # find the position of a in 'Col1'
      where_a = np.where(df['Col1'] == 'a')[0]
      
      # replace a with tuple (4, 5)
      for x in where_a:
          df.set_value(x, 'Col1', (4, 5))
      
         Col0    Col1  Col2
      0     3  (4, 5)     6
      1     7       b     8
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-19
        相关资源
        最近更新 更多