Python:自省,如何验证序列中的值是字符串? [英] Python: introspection, How would I verify that values in a series are strings?

查看:105
本文介绍了Python:自省,如何验证序列中的值是字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于

Building on a previous question, I was told that pd.cut produces strings. For example:

agepreg_cuts = pd.cut(df['agepreg'],[0,20,25,30,pd.np.inf], right=False)
agepreg_cuts[0:10]

上面的代码将为我提供以下值

The above code will give me the following values

0    [30, inf)
1    [30, inf)
2      [0, 20)
3      [0, 20)
4      [0, 20)
5     [25, 30)
6     [25, 30)
7    [30, inf)
8     [25, 30)
9    [30, inf)
Name: agepreg, dtype: category
Categories (4, object): [[0, 20) < [20, 25) < [25, 30) < [30, inf)]

我被告知这些值(例如[25, 30))是字符串,因此我将不得不对其进行解析以获取开始和结束值.我如何验证这些确实是字符串?

I am told that these values (e.g. [25, 30)) are strings and therefore I would have to parse it to get the begin and end values. How would I verify that these are indeed strings?

作为参考,我使用的数据来自 nsfg .免费书籍 thinkstats2

For reference, the data I am using comes from the nsfg. The free book thinkstats2 has companion code and data on github.

在代码"目录中,您可以运行以下行来加载数据框.

From the 'code' directory, you can run the following line to load the dataframe.

import nsfg
df = nsfg.ReadFemPreg()
df

推荐答案

您可以将type函数应用于系列值:

You can apply the type function to the Series values:

In [11]: agepreg_cuts.apply(type)
Out[11]:
0    <class 'str'>
1    <class 'str'>
2    <class 'str'>
3    <class 'str'>
4    <class 'str'>
5    <class 'str'>
6    <class 'str'>
7    <class 'str'>
8    <class 'str'>
9    <class 'str'>
dtype: object

In [12]: agepreg_cuts.apply(type).value_counts()
Out[12]:
<class 'str'>    10
dtype: int64

这篇关于Python:自省,如何验证序列中的值是字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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