熊猫数据框高效查找和替换

时间:2020-08-11 14:14:20

标签: python-3.x pandas replace

我正在处理具有 2000万行 30列的Pandas数据框。

对于此数据帧的每一列,我想做的就是以某种方式遍历行,例如:

  • 如果该元素属于其列中最频繁的5个元素,则保持原样
  • 如果不是,则将其替换为字符串“ Other”。

我觉得我基本上必须遍历每个元素(我有6000万),无论如何,这将花费相当长的时间。 但是,我不知道最好的方法是什么。

我尝试过沙发的东西,其中df是我的数据帧:

df_columns = df.columns.tolist()

top_five = [df[col].value_counts(sort=True).index.tolist()[0:5] for col in df_columns]

L=[[] for i in range(len(df_columns))]
for i, col in (enumerate(df_columns)):
    for j in range(len(df)):
        if df[col][j] not in top_five[i]:
            L[i].append(df[col][j])
    df[col] = df[col].replace(L[i], 'Other')

也许 df.loc numpy.where 更适合于此目的?

预先感谢您:)

2 个答案:

答案 0 :(得分:0)

不建议遍历行。您应该尽可能尝试使用向量化方法。在这种情况下,您可以这样做:

  1. 找到5个最常用的值并存储在数组中
  2. 替换值
for col in df.columns:
    top_five = df[col].value_counts(ascending=False).iloc[0:5].index #Find most frequent values
    df.loc[~df[col].isin(top_five),col] = 'Other'   #Boolean indexing to find the rows with those values, and replacing value by 'Other'

答案 1 :(得分:0)

这是一种使用rank的方法。首先,创建一个测试数据框:

df = pd.DataFrame(
    {'x': ['h'] * 4 + ['i'] * 3 + ['j'] * 2 + ['k'],
     'y': ['d'] * 4 + ['e'] * 3 + ['f'] * 2 + ['g'],
     'z': ['a'] * 4 + ['b'] * 3 + ['c'] * 2 + ['d'],
    })

print(df.tail())
   x  y  z
5  i  e  b
6  i  e  b
7  j  f  c
8  j  f  c
9  k  g  d

现在使用等级来获得每个值的频率;过滤器以查找小于阈值的等级(rank = 1是最常见的),将NA更改为“其他”。另外,我转换为分类类型。这样可能会节省很多空间。

mask = df.rank(method='dense').lt(3) # change 3 to 5 to get 5 most common
df_new = df[mask].fillna('other').astype('category')
print(df_new)

       x      y      z
0      h      d      a
1      h      d      a
2      h      d      a
3      h      d      a
4      i      e      b
5      i      e      b
6      i      e      b
7  other  other  other
8  other  other  other
9  other  other  other

关于分类的引用:

相关问题