【问题标题】:Faster way to loop over and assign to a pandas dataframe?循环并分配给熊猫数据框的更快方法?
【发布时间】:2021-08-31 05:29:10
【问题描述】:

我已经编写了一段代码来循环我的整个数据帧,如果满足条件== '[Blank]',那么它将用一个空字符串'' 替换它。但是,我使用的方法非常慢,我知道必须有更快的方法来做到这一点,但我不确定。我需要能够迭代数据帧并根据条件分配给它。我在下面包含了我的代码:

for i in range(len(df)):
    for j in df.columns:
        if df.loc[i, j] == '[Blank]':
            df.loc[i, j] = ''

【问题讨论】:

  • 你能提供一个你的数据框的最小例子吗?
  • 但是你不能只使用df.replace吗?所以应该是df.replace('[Blank]','')
  • @FiachraBarry 那么,如果你愿意,你可以接受@SifatAmin 的回答,因为那是指df.replace
  • @FiachraBarry 我也添加了我的答案,除了

标签: python pandas performance loops


【解决方案1】:

您可以逐列或从整个数据框替换 BLANK。

df['DataFrame Column'] = df['DataFrame Column'].replace('[BLANK]', '') 
# BY column

for col in df.columns:
 df[col] = df[col].replace('[BLANK]', '')

or
df.replace('[BLANK]', '') # from whole dataframe

【讨论】:

    【解决方案2】:

    只需使用df.replace 替换数据框中的所有值:

    df.replace('[Blank]','')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2017-09-25
      • 2018-03-07
      • 2013-10-23
      相关资源
      最近更新 更多