我有以下格式的熊貓資料框:
col1 col2
0 a A
1 a
2 a A
3 a
4 b
5 b
6 c A
7 c
我想搜索col1至少具有N相應col2 == 'A'值的值。在這種情況下,我想col2用'A's填充列中的其余相應單元格。
讓我們看一個具體的例子。讓我們假設N=1. 在這種情況下,我們檢查,如果有至少一個'A'中col2的各種col1值。對于col1='a',在 中有 2 'A's col2,因此這種情況滿足條件。因此,讓我們col2用'A's填充索引 1 和 3 的行。繼續前進,我們看到 forcol1='b'中沒有'A's col2,因此無需在此處填充任何內容。最后,我們看到,col1='c'恰好有一個'A'在col2。因為這也符合條件,我們將填補與指數7行col2也有'A'。
類似地,當N閾值設定為 2 時,new 'A's 只會添加到索引為 1 和 3 的行中col2,而不會添加到最后一行(索引 7)中。
我假設可能有一種有效的矢量化方式來解決這個問題。目前,我只能考慮遍歷資料框,這對于具有 10 多萬行的原始資料集來說不能很好地擴展。
這是我到目前為止所嘗試的。這適用于這種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']
重現資料幀的代碼:
df = pd.DataFrame(
[['a','A'],['a',''],['a','A'],['a',''],['b',''],['b',''],['c','A'],['c','']],
columns=['col1','col2']
)
uj5u.com熱心網友回復:
這是你要找的嗎?
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
......然后與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
uj5u.com熱心網友回復:
這是一個避免 lambda 函式的解決方案:
N = 1
V = 'A'
df['col2'] = df['col1'].map(df.groupby('col1')['col2'].value_counts().swaplevel()[V].ge(N).map({True:V})).fillna('')
輸出:
>>> 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
uj5u.com熱心網友回復:
這是一個對 numpy 陣列進行操作的解決方案:
def fill_col2(df, N=1):
df_numpy = df.to_numpy()
for val in np.unique(df_numpy[:,0]):
if np.sum(df_numpy[df_numpy[:,0]==val, 1]=='A') >= N:
df_numpy[df_numpy[:,0]==val, 1] = 'A'
return df_numpy[:,1]
df['col2'] = fill_col2(df[['col1', 'col2']])
輸出:
col1 col2
0 a A
1 a A
2 a A
3 a A
4 b
5 b
6 c A
7 c A
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/397668.html
