![](/img/trans.png)
[英]How to write a function to find all rows where value in a column is null when values in dependent columns are not null
[英]Add row values of all columns when a particular column value is null until it gets the not null values?
我有一個像這樣的數據框:
df
col1 col2 col3 col4
A 12 34 XX
B 20 25 PP
B nan nan nan
nan P 54 nan
nan R nan nan
nan nan nan PQ
C D 32 SS
R S 32 RS
如果col1值為null,我想添加其他列的所有值,直到在col1中找到notnull元素為止
我正在尋找的數據框應如下所示:
col1 col2 col3 col4
A 12 34 XX
B 20 25 PP
B PR 54 PQ
C D 32 SS
R S 32 RS
如何使用python / pandas以最有效的方式做
如果要處理字符串之類的所有列,則首先向前填充col1
缺失值,將NaN
替換為空字符串,將所有值轉換為strings
並使用sum
:
df['col1'] = df['col1'].ffill()
df = df.set_index('col1').fillna('').astype(str).sum(level=0).reset_index()
print (df)
col1 col2 col3 col4
0 A 12 34.0 XX
1 B PR 54.0 PQ
2 C D 32.0 SS
print (df.dtypes)
col1 object
col2 object
col3 object
col4 object
dtype: object
如果需要只處理數值列與骨料的方法,例如, mean
使用拉姆達函數if-else
:
df['col1'] = df['col1'].ffill()
c = df.select_dtypes(object).columns
df[c] = df[c].fillna('')
f = lambda x: x.mean() if np.issubdtype(x.dtype, np.number) else ''.join(x)
df = df.groupby('col1').agg(f).reset_index()
print (df)
col1 col2 col3 col4
0 A 12 34.0 XX
1 B PR 54.0 PQ
2 C D 32.0 SS
print (df.dtypes)
col1 object
col2 object
col3 float64
col4 object
dtype: object
編輯:使用新的幫助器列:
df['new'] = df['col1'].notna().cumsum()
df['col1'] = df['col1'].ffill()
c = df.select_dtypes(object).columns
df[c] = df[c].fillna('')
f = lambda x: x.mean() if np.issubdtype(x.dtype, np.number) else ''.join(x)
df = df.groupby(['col1', 'new']).agg(f).reset_index(level=1, drop=True).reset_index()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.