【问题标题】:How to duplicate a row if a condition is matched?如果条件匹配,如何复制一行?
【发布时间】:2022-11-13 02:58:52
【问题描述】:

我有以下数据集

    trade_id    start_date  end_date    factset_entity_id   product_id  product_name    l6_id   multi_assign_flag
0   100000191   2017    NaT 0711GY-E    99996362    Fan Milk - FanYogo  5.015152e+11    0.0
1   100000193   2017    2018    0711GY-E    99996413    Fan Milk - FanDango/Frozen FanDango 5.015151e+11    0.0
2   100000193   2018    2022    0711GY-E    99996413    Fan Milk - FanDango 5.015151e+11    0.0
3   100000193   2022    NaT 0711GY-E    99996413    Fan Milk - FanDango 5.015151e+11    0.0
4   100000231   2016    2018    05NC3S-E    59979529    Ci:z Holdings - Dr. Ci:Labo 5.020102e+11    1.0

我的目标是复制 start_日期和结束_date 不同,例如

1   100000193   2017    2018    0711GY-E    99996413    Fan Milk - FanDango/Frozen FanDango 5.015151e+11    0.0

应该

2017    100000193   0711GY-E    99996413    Fan Milk - FanDango/Frozen FanDango 5.015151e+11    0.0
2018    100000193   0711GY-E    99996413    Fan Milk - FanDango/Frozen FanDango 5.015151e+11    0.0

您知道不使用循环我可以在这里做什么吗?谢谢

我尝试使用简单的循环来做到这一点,这很好,但速度很慢。我想知道 pandas 中是否有可以缓解它的捷径。

【问题讨论】:

    标签: pandas database date


    【解决方案1】:

    使用以下玩具数据框,其中第 0 行和第 2 行具有不同的开始日期和结束日期:

    import pandas as pd
    
    df = pd.DataFrame(
        {
            "trade_id": [100000191, 100000192, 100000193, 100000194, 100000231],
            "start_date": [2017, 2017, 2018, 2022, 2018],
            "end_date": [None, 2017, 2022, 2022, 2018],
            "factset_entity_id": [
                "0711GY-E",
                "0711GY-E",
                "0711GY-E",
                "0711GY-E",
                "05NC3S-E",
            ],
            "product_id": [99996362, 99996413, 99996414, 99996415, 59979529],
        }
    )
    

    这是使用pd.concat 的一种方法:

    df = pd.concat([df, df.loc[df["start_date"] != df["end_date"], :]]).sort_index()
    

    然后,您可以看到第 0 行和第 2 行现在重复了:

    print(df)
    # Output
        trade_id  start_date  end_date factset_entity_id  product_id
    0  100000191        2017       NaN          0711GY-E    99996362
    0  100000191        2017       NaN          0711GY-E    99996362
    1  100000192        2017    2017.0          0711GY-E    99996413
    2  100000193        2018    2022.0          0711GY-E    99996414
    2  100000193        2018    2022.0          0711GY-E    99996414
    3  100000194        2022    2022.0          0711GY-E    99996415
    4  100000231        2018    2018.0          05NC3S-E    59979529
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 2022-06-20
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2021-04-15
      • 2016-06-28
      • 1970-01-01
      相关资源
      最近更新 更多