【问题标题】:Change of element in column not updating in data frame列中元素的更改未在数据框中更新
【发布时间】:2018-12-30 06:41:40
【问题描述】:

我正在尝试更新 pandas 数据框列中的名称。我要:

[输入]

B17.31
107.34
34
B50.56

[输出]

B17.31
B107.34
B34
B50.56

我使用的代码是:

for file in df1.loc[:, '#filename']:
    new = str(file)
    if new[0] != 'B':
       final = new[:0] + 'B' + new[0:]
    else:
        final = new

    print((final))
    df1.replace(new, final)

print(df1['#filename'])
df1.to_csv('updated_name_data.csv') 

我不知道为什么它会打印出更新后的名称,但不会在数据框或 csv 中更新。任何帮助或正确方向的指针将不胜感激。

【问题讨论】:

    标签: python pandas rename


    【解决方案1】:

    这应该可行:

    for file in df1.loc[:, '#filename']:
        new = str(file)
        if new[0] != 'B':
           final = new[:0] + 'B' + new[0:]
        else:
            final = new
    
        print((final))
        df1.replace(new, final,inplace=True)# yuo are not using inplace=True, this is required as otherwise this will return the old dataframe after replacement
    
        print(df1['#filename'])
        df1.to_csv('updated_name_data.csv')
    

    【讨论】:

    • @p.strain 欢迎您,如果它解决了您的问题,请接受我的回答 :)
    • @p.strain - 嗯,使用循环有什么原因吗?没问题就是慢?还是小数据,没问题?我有点好奇……
    • 我将循环用作具有 10,000 个名称的数据集。对python来说相对较新,所以如果有更快的方法肯定会试一试。
    • @p.strain 肯定有更快的方法。 for 循环非常耗时
    【解决方案2】:

    您的目标应该是使用矢量化操作而不是手动循环。例如,您可以隔离数值并以"B"为前缀:

    s = pd.Series(['B17.31', 107.34, 34, 'B50.56'])
    
    mask = pd.to_numeric(s, errors='coerce').notnull()
    s.loc[mask] = 'B' + s.astype(str)
    
    print(s)
    
    0     B17.31
    1    B107.34
    2        B34
    3     B50.56
    dtype: object
    

    【讨论】:

      【解决方案3】:

      在 pandas 中最好避免循环,因为速度慢,最好使用矢量化函数。

      因此您可以通过str.startswith 创建布尔掩码,然后使用numpy.whereB 添加到原始列:

      mask = df1['#filename'].astype(str).str.startswith('B')
      df1['#filename'] = np.where(mask, df1['#filename'], 'B' + df1['#filename'].astype(str))
      

      ~ 的另一个类似的反转掩码解决方案:

      df1.loc[~mask, '#filename'] =  'B' + df1['#filename'].astype(str)
      

      print (df1)
       #filename
      0    B17.31
      1   B107.34
      2       B34
      3    B50.56
      

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 1970-01-01
        • 2019-09-20
        • 2015-04-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-28
        • 1970-01-01
        相关资源
        最近更新 更多