gpt4 book ai didi

python - 如何在忽略 "None"的情况下将多个 pandas 列对象类型值合并到一列中?

转载 作者:太空狗 更新时间:2023-10-30 01:52:52 24 4
gpt4 key购买 nike

起始数据框:

pd.DataFrame({'col1': ['one', 'None', 'None'], 'col2': ['None', 'None', 'six'], 'col3': ['None', 'eight', 'None']})

enter image description here

最终目标:

pd.DataFrame({'col4': ['one', 'eight', 'six']})

enter image description here

我尝试做的事情:

df['col1'].map(str)+df['col2'].map(str)+df['col3'].map(str)

enter image description here

如何在忽略“无”值的情况下将多个 pandas 列对象类型值合并到一列中?顺便说一句,在此数据集中,最终数据框单元格中的值永远不会超过一个。

最佳答案

您有字符串 None,而不是实际的空值,因此您需要先替换它们。

选项 1
replace/掩码/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
替换 + 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

关于python - 如何在忽略 "None"的情况下将多个 pandas 列对象类型值合并到一列中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com