首页 > 解决方案 > 根据最大计数在 Dataframe 中复制数据

问题描述

dfaugment = dftrain.sort_values('text', ascending=False).groupby('Category')
countdict = dict(dfaugment['Category'].count())
countdictmax = max(countdict.values())
shortdict = {}
for key, value in countdict.items():
    if value <= countdictmax:
    shortdict[key] = countdictmax - value

我正在尝试根据类别字段的最大计数为不同的类别字段生成重复行。

例如:

Category | text 
Shoes | "aasdb"
Shoes | "frrrd"
Shoes | "ertbt"
Shoes | "erbete"
Shoes | "ervsss"
Sticks | "14345"
Sticks | "33445"

应该成为

Category | text 
Shoes | "aasdb"
Shoes | "frrrd"
Shoes | "ertbt"
Shoes | "erbete"
Shoes | "ervsss"
Sticks | "14345"
Sticks | "33445"
Sticks | "14345" #new row (duplicated from above data) 
Sticks | "33445" #new row (duplicated from above data) 
Sticks | "14345" #new row (duplicated from above data) 

标签: pythonpython-3.xpandas

解决方案


您可以使用itertools.cycle &获得重复填充zip

df = pd.DataFrame(
    [('Shoes',"aasdb"), 
     ('Shoes',"frrrd"),
     ('Shoes',"ertbt"),
     ('Shoes',"erbete"),
     ('Shoes',"ervsss"),
     ('Sticks',"14345"),
     ('Sticks',"33445")], 
    columns=['Category', 'text']
)

首先我们找到 max_size,然后我们构造我们的元组列表并传递给 DataFrame 构造函数。

max_size = df.groupby('Category').size().max()
pd.DataFrame(
    [(a, b) 
     for k in df.Category.drop_duplicates()
     for a, b in zip([k]*max_size, cycle(df.text[df.Category==k]))]
    , columns = df.columns
)

这输出:

  Category    text
0    Shoes   aasdb
1    Shoes   frrrd
2    Shoes   ertbt
3    Shoes  erbete
4    Shoes  ervsss
5   Sticks   14345
6   Sticks   33445
7   Sticks   14345
8   Sticks   33445
9   Sticks   14345

变体1:

我认为前向填充就足够了

转发填充,使用iterools.zip_longeston Category,但不要 cycleon text& thenffill

pd.DataFrame(
    [(a, b) 
     for k in df.Category.drop_duplicates()
     for a, b in zip_longest([k]*max_size, df.text[df.Category==k])]
    , columns = df.columns).ffill()

这输出:

  Category    text
0    Shoes   aasdb
1    Shoes   frrrd
2    Shoes   ertbt
3    Shoes  erbete
4    Shoes  ervsss
5   Sticks   14345
6   Sticks   33445
7   Sticks   33445
8   Sticks   33445
9   Sticks   33445

变体 2:

随机选择重复的样本

我不确定这里的确切含义,但这是一种随机填充的方法。

这开始类似于前向填充。

df2 = pd.DataFrame(
    [(a, b) 
     for k in df.Category.drop_duplicates()
     for a, b in zip_longest([k]*max_size, df.text[df.Category==k])]
    , columns = df.columns
)

接下来为每组获取一个text大小的样本max_size并将它们堆叠起来。并合并使用pandas.combine_first

fill = pd.concat(
    [df.text[df.Category==k].sample(max_size, replace=True)
     for k in df.Category.drop_duplicates()]
).reset_index(drop=True)
df2.text = df2.text.combine_first(fill)

示例 df2 输出(可能对您有所不同,因为我没有为样本设置种子)

  Category    text
0    Shoes   aasdb
1    Shoes   frrrd
2    Shoes   ertbt
3    Shoes  erbete
4    Shoes  ervsss
5   Sticks   14345
6   Sticks   33445
7   Sticks   14345
8   Sticks   14345
9   Sticks   33445

推荐阅读