【问题标题】:How to modify cells in a pandas DataFrame?如何修改 pandas DataFrame 中的单元格?
【发布时间】:2016-12-26 08:06:38
【问题描述】:

我需要更改 DataFrame 中的各个元素。我尝试做这样的事情,但它不起作用:

for index, row in df.iterrows():
    if df.at[row, index] == 'something':
        df.at[row, index] = df.at[row, index] + 'add a string'
    else:
        df.at[row, index] = df.at[row, index] + 'add a value'

我该怎么做?

【问题讨论】:

    标签: python string pandas dataframe conditional-statements


    【解决方案1】:

    如果需要修改DataFrame 中的所有列,请使用numpy.whereDataFrame 构造函数,因为where 返回numpy array

    df = pd.DataFrame(np.where(df == 'something', df + 'add a string', df + 'add a value'), 
                      index=df.index, 
                      columns=df.columns)
    

    如果只有一列col

    df['col'] = np.where(df['col'] == 'something', 
                         df['col'] + 'add a string', 
                         df['col'] + 'add a value')
    

    示例:

    df = pd.DataFrame({'col': ['a', 'b', 'a'], 'col1': ['a', 'b', 'b']})
    print (df)
      col col1
    0   a    a
    1   b    b
    2   a    b
    
    df = pd.DataFrame(np.where(df == 'a', df + 'add a string', df + 'add a value'), 
                      index=df.index, 
                      columns=df.columns)
    print (df)
                 col           col1
    0  aadd a string  aadd a string
    1   badd a value   badd a value
    2  aadd a string   badd a value
    

    df['col'] = np.where(df['col'] == 'a', 
                         df['col'] + 'add a string', 
                         df['col'] + 'add a value')
    
    print (df)
                 col col1
    0  aadd a string    a
    1   badd a value    b
    2  aadd a string    b
    

    【讨论】:

      【解决方案2】:

      您可以使用.ix 并应用如下函数:

      import pandas as pd
      
      D = pd.DataFrame({'A': ['a', 'b', 3,7,'b','a'], 'B': ['a', 'b', 3,7,'b','a']})
      
      D.ix[D.index%2 == 0,'A'] = D.ix[D.index%2 == 0,'A'].apply(lambda s: s+'x' if isinstance(s,str) else s+1)
      
      D.ix[D.index[2:5],'B'] = D.ix[D.index[2:5],'B'].apply(lambda s: s+'y' if isinstance(s,str) else s-1)
      

      第一个示例将 x 附加到每个字符串,或者将 1 附加到 A 列上每个偶数索引的每个非字符串。

      第二个示例将 y 附加到每个字符串,或者从 B 列上索引 2、3、4 的每个非字符串中减去 1。

      原始框架:

         A  B
      0  a  a
      1  b  b
      2  3  3
      3  7  7
      4  b  b
      5  a  a
      

      修改框架:

          A   B
      0  ax   a
      1   b   b
      2   4   2
      3   7   6
      4  bx  by
      5   a   a
      

      【讨论】:

        猜你喜欢
        • 2019-08-06
        • 1970-01-01
        • 2014-04-04
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多