【问题标题】:How to skip NaN values when splitting up a column拆分列时如何跳过 NaN 值
【发布时间】:2021-09-28 01:28:52
【问题描述】:

我正在尝试根据分隔符将一列拆分为两列。该列目前具有由“-”分隔的文本。列中的一些值是 NaN,所以当我运行下面的代码时,我收到以下错误消息:ValueError: Columns must be same length as key.

我不想删除 NaN 值,但不确定如何跳过它们以便这种拆分工作。

我现在的代码是:

df[['A','B']] = df['A'].str.split('-',expand=True)

【问题讨论】:

标签: python pandas dataframe split


【解决方案1】:

您的代码适用于 NaN 值,但您必须使用 n=1 作为 str.split 的参数:

假设这个数据框:

df = pd.DataFrame({'A': ['hello-world', np.nan, 'raise-an-exception']}
print(df)

# Output:
                    A
0         hello-world
1                 NaN
2  raise-an-exception

可重现的错误:

df[['A', 'B']] = df['A'].str.split('-', expand=True)
print(df)

# Output:
...
ValueError: Columns must be same length as key

使用n=1

df[['A', 'B']] = df['A'].str.split('-', n=1, expand=True)
print(df)

# Output:
       A             B
0  hello         world
1    NaN           NaN
2  raise  an-exception

另一种方法是生成更多列:

df1 = df['A'].str.split('-', expand=True)
df1.columns = df1.columns.map(lambda x: chr(x+65))
print(df1)

# Output:
       A      B          C
0  hello  world       None
1    NaN    NaN        NaN
2  raise     an  exception

【讨论】:

  • 感谢您非常详尽的解释。这非常有效!
【解决方案2】:

也许用 loc 过滤掉它们:

df.loc[df['A'].notna(), ['A','B']] = df.loc[df['A'].notna(), 'A'].str.split('-',expand=True)

【讨论】:

    猜你喜欢
    • 2014-02-19
    • 2021-04-18
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2010-12-28
    相关资源
    最近更新 更多