python - Pandas Dataframe,当某些行可能有超过 1 ","时,如何将一列分成两列 ","

标签 python pandas dataframe

我有一个数据框。其中一列是 CITYSTATE 的组合。我想将此列拆分为两列,CITYSTATE 使用:

df['CITY'],df['STATE'] = df['WORKSITE'].str.split(",")

我收到了这个错误:

ValueError Traceback (most recent call last) in () ----> 1 df['CITY'],df['STATE'] = df['WORKSITE'].str.split(",")

ValueError: too many values to unpack (expected 2)

那么,我想知道是否有一种方法可以忽略异常或检测哪一行不起作用?

最佳答案

split 调用中设置 n=2 并有效地使用 str 方法:

import pandas as pd

x = ['New York, NY', 'Los Angeles, CA', 'Kansas City, KS, US']

df = pd.DataFrame(x, columns=['WORKSITE'])

df['CITY'], df['STATE'] = df['WORKSITE'].str.split(',', 2).str[0:2].str

print df

输出

              WORKSITE         CITY STATE
0         New York, NY     New York    NY
1      Los Angeles, CA  Los Angeles    CA
2  Kansas City, KS, US  Kansas City    KS

我通过查看 this answer 得到了一些帮助至 this question .

关于python - Pandas Dataframe,当某些行可能有超过 1 ","时,如何将一列分成两列 ",",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43548840/

相关文章:

python - 使用递归来反转 python 中的列表?

python - 滚动 Matplotlib 颜色条

python - 删除节点lxml python

Python numpy : Updating multiple columns using lists failed in V1. 10.1

python - 在 Pandas 中创建和删除列

python - Scrapy 将返回的项目存储在变量中以在主脚本中使用

python - Pandas groupby 到嵌套的 json

python - 如何根据不同的列更改一列中的值?

python - 时间序列中第一条记录的 Pandas Diff(),缺失数据返回 NaN

pandas - 如何将新列中的值附加到 Pandas 中的空行