【问题标题】:Traceback when using pandas.Series.str.split: Must have equal len keys and value when setting with an iterable使用 pandas.Series.str.split 时的回溯:使用可迭代设置时必须具有相等的 len 键和值
【发布时间】:2022-01-20 15:17:52
【问题描述】:

我有一个看起来像这样的数据框,我想通过将key 列拆分为_ 作为分隔符来创建 5 个额外的列

                                             key   value
VALUETIME                                               
2021-12-17 11:00:00   BE_G_av_211214170724_a  5312.0
2021-12-17 12:00:00   BE_G_av_211214170724_a  5312.0
2021-12-17 13:00:00   BE_G_av_211214170724_a  5312.0
2021-12-17 14:00:00   BE_G_av_211214170724_a  5312.0
2021-12-17 15:00:00   BE_G_av_211214170724_a  5312.0
                                         ...     ...
2022-02-15 06:00:00  NL_G_gen_211205212740_a  3804.0
2022-02-15 07:00:00  NL_G_gen_211205212740_a  5260.0
2022-02-15 08:00:00  NL_G_gen_211205212740_a  6043.0
2022-02-15 09:00:00  NL_G_gen_211205212740_a  6184.0

我尝试了以下所有方法

df_a_ccgt_m_fc_long[['test1', 'test2', 'test3', 'test4', 'test5']] = df_a_ccgt_m_fc_long['key'].str.split('_')

df_a_ccgt_m_fc_long[['test1', 'test2', 'test3', 'test4', 'test5']] = df_a_ccgt_m_fc_long['key'].str.split(pat = '_')

但两者都给了我相同的回溯:

Traceback (most recent call last):

  File "C:\Users\AppData\Roaming\Python\Python37\site-packages\pandas\core\indexing.py", line 1712, in _setitem_with_indexer_split_path
    "Must have equal len keys and value "

ValueError: Must have equal len keys and value when setting with an iterable

【问题讨论】:

    标签: python pandas string


    【解决方案1】:

    我发现通过添加 expand=True 它可以解决我的问题,尽管我不确定为什么,因为我的数据似乎总是有 4 个 _ 并且在 5 部分中没有任何缺失数据。

    【讨论】:

    • 如果没有expand=True,您只会得到 1 列(包含字符串列表),这就是您收到错误的原因。您不能以这种方式将 1 列分配给 4 列。
    猜你喜欢
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2022-10-03
    • 2020-01-08
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多