将 2 列中的值合并为 Pandas 数据框中的单列 [英] Coalesce values from 2 columns into a single column in a pandas dataframe
本文介绍了将 2 列中的值合并为 Pandas 数据框中的单列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种行为类似于 T-SQL 中的合并的方法.我有 2 列(A 列和 B 列)在 Pandas 数据框中稀疏填充.我想使用以下规则创建一个新列:
I'm looking for a method that behaves similarly to coalesce in T-SQL. I have 2 columns (column A and B) that are sparsely populated in a pandas dataframe. I'd like to create a new column using the following rules:
- 如果列 A 中的值不为空,则将该值用于新列 C
- 如果 A 列中的值为空,则将 B 列中的值用于新的 C 列
就像我提到的,这可以通过合并函数在 MS SQL Server 中完成.我还没有为此找到一个好的pythonic方法;存在吗?
Like I mentioned, this can be accomplished in MS SQL Server via the coalesce function. I haven't found a good pythonic method for this; does one exist?
推荐答案
使用 combine_first():
In [16]: df = pd.DataFrame(np.random.randint(0, 10, size=(10, 2)), columns=list('ab'))
In [17]: df.loc[::2, 'a'] = np.nan
In [18]: df
Out[18]:
a b
0 NaN 0
1 5.0 5
2 NaN 8
3 2.0 8
4 NaN 3
5 9.0 4
6 NaN 7
7 2.0 0
8 NaN 6
9 2.0 5
In [19]: df['c'] = df.a.combine_first(df.b)
In [20]: df
Out[20]:
a b c
0 NaN 0 0.0
1 5.0 5 5.0
2 NaN 8 8.0
3 2.0 8 2.0
4 NaN 3 3.0
5 9.0 4 9.0
6 NaN 7 7.0
7 2.0 0 2.0
8 NaN 6 6.0
9 2.0 5 2.0
这篇关于将 2 列中的值合并为 Pandas 数据框中的单列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文