pandas数据框中整个列的子字符串 [英] substring of an entire column in pandas dataframe

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

问题描述

我有一个熊猫数据框"df".在此数据帧中,我有多个列,其中之一必须为子字符串. 可以说列名是"col". 我可以像下面那样运行"for"循环并对该列进行子串化:

I have a pandas dataframe "df". In this dataframe I have multiple columns, one of which I have to substring. Lets say the column name is "col". I can run a "for" loop like below and substring the column:

for i in range(0,len(df)):
  df.iloc[i].col = df.iloc[i].col[:9]

但是我想知道,是否有一个选项,我不必使用"for"循环,而直接使用属性进行操作.我有大量的数据,如果这样做,数据将花费很长时间.

But I wanted to know, if there is an option where I don't have to use a "for" loop, and do it directly using an attribute.I have huge amount of data, and if I do this, the data will take a very long time process.

推荐答案

在方括号内使用str访问器:

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

str.slice :

df['col'] = df['col'].str.slice(0, 9)

这篇关于pandas数据框中整个列的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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