我有一个以下格式的 pandas 数据框:
col1 col2
0 a A
1 a
2 a A
3 a
4 b
5 b
6 c A
7 c
Run Code Online (Sandbox Code Playgroud)
我想搜索col1至少具有N对应col2 == 'A'值的值。col2在这种情况下,我想用 s 填充列中其余相应单元格'A'。
让我们看一个具体的例子。让我们假设一下N=1。在本例中,我们检查各个'A'值是否至少有一个。对于, 中有 2 个s ,因此这种情况满足条件。因此,让我们用s填充索引为 1 和 3 的行。继续,我们看到对于, 中没有s ,因此不需要在这里填写任何内容。最后,我们看到 for中正好有一个。由于这也满足条件,我们也将用填充索引为 7 的行。col2col1col1='a''A'col2col2'A'col1='b''A'col2col1='c''A'col2col2'A'
同样,当N阈值设置为 2 时,新的'A's 只会添加到 中索引为 1 和 3 的行col2,而不会添加到最后一行(索引 7)。
我假设可能有一种有效的矢量化方法来解决这个问题。目前,我只能考虑迭代数据帧,这对于具有数十或数千行的原始数据集来说不能很好地扩展。
这是我到目前为止所尝试的。这适用于这种N=1情况,尽管我没有设法弄清楚如何将其推广到任何N阈值,更不用说如何更好地实现它了:
df = df.sort_values(['col1','col2'], ascending=[True,False]).reset_index(drop=True)
for idx, row in df.iloc[1:,:].iterrows():
if df.loc[idx,'col1'] == df.loc[idx-1,'col1'] and df.loc[idx,'col2']=='' and df.loc[idx-1,'col2']!='':
df.loc[idx,'col2'] = df.loc[idx-1,'col2']
Run Code Online (Sandbox Code Playgroud)
重现数据帧的代码:
df = pd.DataFrame(
[['a','A'],['a',''],['a','A'],['a',''],['b',''],['b',''],['c','A'],['c','']],
columns=['col1','col2']
)
Run Code Online (Sandbox Code Playgroud)
小智 6
这是您要找的吗?
N = 1
value = 'A'
df.loc[df.groupby('col1')['col2'].transform(lambda x: sum(x == value) >= N), 'col2'] = value
print(df)
col1 col2
0 a A
1 a A
2 a A
3 a A
4 b
5 b
6 c A
7 c A
Run Code Online (Sandbox Code Playgroud)
...然后与N = 2...
col1 col2
0 a A
1 a A
2 a A
3 a A
4 b
5 b
6 c A
7 c
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
682 次 |
| 最近记录: |