获取 pandas 数据框列中值的长度 [英] Get length of values in pandas dataframe column

查看:101
本文介绍了获取 pandas 数据框列中值的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取下面提到的数据帧中每个 zipCd 值的长度.当我运行下面的代码时,每条记录都会得到 958.我期待得到更像4"的东西.有没有人看到问题是什么?

I'm trying to get the length of each zipCd value in the dataframe mentioned below. When I run the code below I get 958 for every record. I'm expecting to get something more like '4'. Does anyone see what the issue is?

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.maplen 内置.

One way is to convert to string and use pd.Series.map with len built-in.

pd.Series.str 用于矢量化字符串函数,而 pd.Series.astype 用于更改列类型.

pd.Series.str is used for vectorized string functions, while pd.Series.astype is used to change column type.

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:

A more explicit alternative is to use np.log10:

df['ZipLen'] = np.floor(np.log10(df['ZipCode'].values)).astype(int) + 1

这篇关于获取 pandas 数据框列中值的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆