首页 > 解决方案 > 拆分列时如何跳过 NaN 值

问题描述

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

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

我现在的代码是:

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

标签: pythonpandasdataframesplit

解决方案


您的代码适用于 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

推荐阅读