你有字符串Nones,而不是实际的空值,所以你需要先替换它们。
选项 1
replace/mask/where + fillna + agg
df.replace('None', np.nan).fillna('').agg(''.join, axis=1).to_frame('col4')
或者,
df.mask(df.eq('None')).fillna('').agg(''.join, axis=1).to_frame('col4')
或者,
df.where(df.ne('None')).fillna('').agg(''.join, axis=1).to_frame('col4')
col4
0 one
1 eight
2 six
选项 2
replace + pd.notnull
v = df.replace('None', np.nan).values.ravel()
pd.DataFrame(v[pd.notnull(v)], columns=['col4'])
col4
0 one
1 eight
2 six
选项 3
利用 Divakar 出色的justify 功能的解决方案:
pd.DataFrame(justify(df.values, invalid_val='None')[:, 0], columns=['col4'])
col4
0 one
1 eight
2 six
参考
(注意,您需要稍微修改函数才能很好地处理字符串数据。)
def justify(a, invalid_val=0, axis=1, side='left'):
"""
Justifies a 2D array
Parameters
----------
A : ndarray
Input array to be justified
axis : int
Axis along which justification is to be made
side : str
Direction of justification. It could be 'left', 'right', 'up', 'down'
It should be 'left' or 'right' for axis=1 and 'up' or 'down' for axis=0.
"""
if invalid_val is np.nan:
mask = ~np.isnan(a)
else:
mask = a!=invalid_val
justified_mask = np.sort(mask,axis=axis)
if (side=='up') | (side=='left'):
justified_mask = np.flip(justified_mask,axis=axis)
out = np.full(a.shape, invalid_val, dtype='<U8') # change to be made is here
if axis==1:
out[justified_mask] = a[mask]
else:
out.T[justified_mask.T] = a.T[mask.T]
return out