熊猫聚结多柱,NaN

时间:2019-11-18 19:49:38

标签: python pandas coalesce

我想使用熊猫moths : 120 permutations are : 6 permutations insect : 720 permutations teddy : 60 permutations bears : 120 permutations 4列。我已经尝试过了:

coalesce

当我使用它时,它返回:

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

字段+-------+--------+-------+------+------+------------+------------------+ | 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)) 作为密钥的一部分。

2 个答案:

答案 0 :(得分:1)

尝试一下:

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

答案 1 :(得分:1)

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

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