我有一个数据框。其中一列是CITY
和STATE
的组合。我想使用以下内容将此列拆分为两列CITY
和STATE
df['CITY'],df['STATE'] = df['WORKSITE'].str.split(",")
我收到了这个错误:
ValueError Traceback(最近一次调用 最后)in() ----> 1 df ['CITY'],df ['STATE'] = df ['WORKSITE']。str.split(“,”)
ValueError:解压缩的值太多(预期2)
所以,我想知道是否有一种方法可以忽略异常或检测哪一行不起作用?
答案 0 :(得分:2)
在#!/bin/bash
set -e
ask() {
local input
until
read -rp "$1 > " input >&2 || return 1
grep -q -P "$2" <<< "$input"
do
echo "Invalid answer. Try again" >&2
done
printf '%s\n' "$input"
}
ask_fqdn() {
ask "$1" '(?=^.{1,254}$)(^(?>(?!\d+\.)[a-z0-9_\-]{1,63}\.?)+(?:[a-z]{2,})$)'
}
fqdn=$(ask_fqdn "Enter first FQDN")
echo "You wrote $fqdn"
fqdn=$(ask_fqdn "Enter second FQDN")
echo "This time it was $fqdn"
number=$(ask "And now a number because why not" '^\d+$')
echo "So $number"
来电中设置n=2
并有效使用split
方法:
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
我从this answer到this question获得了一些帮助。