使用Pandas将多列转换为一个

2024-04-26 14:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧结构: dataframe snapshot

我想知道在pandas中最有效的方法是创建一个新列“stage”,该列提取四列中非“None”的任何值,并将该值用于“stage”列。在stage列提取出每行中非None的任何值后,可以删除其余四列。在

以下是每个相关列的唯一值的另一个快照: unique values

请注意,相关列中的值是字符串类型,而None实际上不是Nonetype。在


Tags: 数据方法字符串none类型pandas结构快照
2条回答

考虑combine_first,假设None不是字符串文本'None'。在

df['stage'] = df['doggo'].combine_first(df['floorfer'])\
                         .combine_first(df['pupper'])\ 
                         .combine_first(df['puppo'])

或者,对于干式er方法,使用reduce

^{pr2}$
df['New']=df[['A','B','C']].replace('None','').sum(1)
df
Out[1477]: 
      A     B     C New
0  None     B  None   B
1     A  None  None   A
2  None  None     C   C

数据输入

^{pr2}$

相关问题 更多 >