我试图获取下面提到的数据框中每个 zipCd 值的长度。当我运行下面的代码时,每条记录都得到 958。我期待得到更像“4”的东西。有人看出问题是什么吗?
Code:
zipDfCopy['zipCd'].str.len()
Data:
print zipDfCopy[1:5]
Zip Code Place Name State State Abbreviation County \
1 544 Holtsville New York NY Suffolk
2 1001 Agawam Massachusetts MA Hampden
3 1002 Amherst Massachusetts MA Hampshire
4 1003 Amherst Massachusetts MA Hampshire
Latitude Longitude zipCd
1 40.8154 -73.0451 0 501\n1 544\n2 1001...
2 42.0702 -72.6227 0 501\n1 544\n2 1001...
3 42.3671 -72.4646 0 501\n1 544\n2 1001...
4 42.3919 -72.5248 0 501\n1 544\n2 1001...
一种方法是转换为字符串并使用pd.Series.map
with len
内置。
pd.Series.str https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.html用于向量化字符串函数,而pd.Series.astype https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html用于更改列类型。
import pandas as pd
df = pd.DataFrame({'ZipCode': [341, 4624, 536, 123, 462, 4642]})
df['ZipLen'] = df['ZipCode'].astype(str).map(len)
# ZipCode ZipLen
# 0 341 3
# 1 4624 4
# 2 536 3
# 3 123 3
# 4 462 3
# 5 4642 4
更明确的替代方法是使用np.log10
:
df['ZipLen'] = np.floor(np.log10(df['ZipCode'].values)).astype(int) + 1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)