python - 拆分列时如何跳过 NaN 值
问题描述
我正在尝试根据分隔符将一列拆分为两列。该列目前具有由“-”分隔的文本。列中的一些值是 NaN,所以当我运行下面的代码时,我收到以下错误消息: ValueError: Columns must be same length as key.
我不想删除 NaN 值,但不确定如何跳过它们以便这种拆分工作。
我现在的代码是:
df[['A','B']] = df['A'].str.split('-',expand=True)
解决方案
您的代码适用于 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
推荐阅读
- python - 如何理解我的 Twitter 数据框枢轴
- css - React Material-UI Table如何为Table设置“border-spacing”以具有分隔的行
- api - 如何解决我的 ExtJS 商店中的 CORS 问题
- javascript - 如何在 2 个地图函数中等待并从 mongoDB 检索文档
- docker - nginx反向代理后面的Docker Flask应用程序发送404
- kubernetes - 获取 kubernetes 中 coredns pod 的 /etc/resolv.conf 的内容
- javascript - 当用户输入一个字母时如何防止搜索?
- algorithm - 在 CSES 问题集酒店查询上得到错误答案
- javascript - 从输入值中获取未定义
- python - Django - 我如何将模型称为字符串?