Pandas 合并多列,NaN

Pandas Coalesce Multiple Columns, NaN

我想 coalesce 4 列使用 pandas。我试过这个:

final['join_key'] = final['book'].astype('str') + final['bdr'] + final['cusip'].fillna(final['isin']).fillna(final['Deal'].astype('str')).fillna(final['Id'])

当我使用它时 returns:

+-------+--------+-------+------+------+------------+------------------+
| book  |  bdr   | cusip | isin | Deal |     Id     |     join_key     |
+-------+--------+-------+------+------+------------+------------------+
| 17236 | ETFROS |       |      |      | 8012398421 | 17236.0ETFROSnan |
+-------+--------+-------+------+------+------------+------------------+

字段 Id 没有正确附加到我的 join_key 字段。

如有任何帮助,我们将不胜感激。

更新:

+------------+------+------+-----------+--------------+------+------------+----------------------------+
|  endOfDay  | book | bdr  |   cusip   |     isin     | Deal |     Id     |          join_key          |
+------------+------+------+-----------+--------------+------+------------+----------------------------+
| 31/10/2019 |   15 | ITOR | 371494AM7 | US371494AM77 |  161 | 8013210731 | 20191031|15|ITOR|371494AM7 |
| 31/10/2019 |   15 | ITOR |           |              |      | 8011898573 | 20191031|15|ITOR|          |
| 31/10/2019 |   15 | ITOR |           |              |      | 8011898742 | 20191031|15|ITOR|          |
| 31/10/2019 |   15 | ITOR |           |              |      | 8011899418 | 20191031|15|ITOR|          |
+------------+------+------+-----------+--------------+------+------------+----------------------------+

df['join_key'] = ("20191031|" + df['book'].astype('str') + "|" + df['bdr'] + "|" + df[['cusip', 'isin', 'Deal', 'id']].bfill(1)['cusip'].astype(str))

出于某种原因,此代码未将 Id 作为密钥的一部分。

试试这个:

import pandas as pd
import numpy as np

# setup (ignore)   
final = pd.DataFrame({
    'book': [17236],
    'bdr': ['ETFROS'],
    'cusip': [np.nan],
    'isin': [np.nan],
    'Deal': [np.nan],
    'Id': ['8012398421'],
})

# answer
final['join_key'] = final['book'].astype('str') + final['bdr'] + final['cusip'].fillna(final['isin']).fillna(final['Deal']).fillna(final['Id']).astype('str')

输出

    book    bdr     cusip   isin    Deal    Id          join_key
0   17236   ETFROS  NaN     NaN     NaN     8012398421  17236ETFROS8012398421

cusip 的最后一个链 fillna 太复杂了。您可以将其更改为 bfill

final['join_key'] = (final['book'].astype('str') + 
                     final['bdr'] + 
                     final[['cusip', 'isin', 'Deal', 'Id']].bfill(1)['cusip'].astype(str))