python - 根据最大计数在 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)
解决方案
您可以使用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_longest
on Category
,但不要 cycle
on 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
推荐阅读
- uwp - UWP VPN 配置文件未创建 VPN 连接
- python - 如何旋转相机录制的视频?
- http - grpc - 如果启用了 https,是否需要 TLS?
- python - Slug 生成器不会为表格内容生成 slug
- google-compute-engine - 如何在 gce 中禁用整个集群的日志
- python - .XML 文件可以从 .txt 或 .py 中的变量设置值吗?
- ldap - AzureAD 组 objectid 的匹配 LDAP 属性
- canvas - Flutter - 在照片上绘图
- java - 我的应用程序无法在 java 8u231 上启动
- c++ - “c++ 完整指南”一书第 252 页的错字?