我熟悉"矢量化"的概念,以及熊猫如何使用矢量化技术来加速计算.矢量化函数在整个系列或DataFrame上广播操作,以实现比传统迭代数据更大的加速.
但是,我很惊讶地看到很多代码(包括Stack Overflow的答案)提供了解决问题的方法,这些问题涉及使用for循环和列表推导来循环数据.阅读完文档后,对API有了不错的理解,我认为循环是"坏的",并且应该"永远"迭代数组,系列或DataFrame.那么,为什么我会不时地看到用户提出循环解决方案呢?
因此,要总结......我的问题是:
是否for循环真正的"坏"?如果不是,在什么情况下它们会比使用更传统的"矢量化"方法更好?1
1 - 虽然这个问题确实听起来有点宽泛,但事实是,当for循环通常比传统的迭代数据更好时,存在非常具体的情况.这篇文章旨在为后人捕捉这一点.
我正在尝试在数据框中创建一个新列,其中包含相应行的字数.我正在寻找单词的总数,而不是每个不同单词的频率.我认为会有一个简单/快速的方法来做到这一点共同的任务,但周围的Googling和阅读SO职位(一小撮后1,2,3,4)我卡住了.我已经尝试了在链接的SO帖子中提出的解决方案,但是回到了很多属性错误.
words = df['col'].split()
df['totalwords'] = len(words)
Run Code Online (Sandbox Code Playgroud)
结果是
AttributeError: 'Series' object has no attribute 'split'
Run Code Online (Sandbox Code Playgroud)
和
f = lambda x: len(x["col"].split()) -1
df['totalwords'] = df.apply(f, axis=1)
Run Code Online (Sandbox Code Playgroud)
结果是
AttributeError: ("'list' object has no attribute 'split'", 'occurred at index 0')
Run Code Online (Sandbox Code Playgroud) code: df['review'].head()
index review
output: 0 These flannel wipes are OK, but in my opinion
Run Code Online (Sandbox Code Playgroud)
我想从数据框的列中删除标点符号并创建一个新列.
code: import string
def remove_punctuations(text):
return text.translate(None,string.punctuation)
df["new_column"] = df['review'].apply(remove_punctuations)
Error:
return text.translate(None,string.punctuation)
AttributeError: 'float' object has no attribute 'translate'
Run Code Online (Sandbox Code Playgroud)
我正在使用python 2.7.任何的意见都将会有帮助.
嘿,我已经看到了这个链接,但在那里他们已经使用了re模块,这就是我在这里发布的原因.希望您理解并删除副本.
这是链接.我想用re模块.
表:
A B C D
1 Q! W@ 2
2 1$ E% 3
3 S2# D! 4
Run Code Online (Sandbox Code Playgroud)
在这里,我想从column B和删除特殊字符C.我已经使用.transform()但我想re尽可能使用它,但我收到了错误.
输出:
A B C D E F
1 Q! W@ 2 Q W
2 1$ E% 3 1 E
3 S2# D! 4 S2 D
Run Code Online (Sandbox Code Playgroud)
我的代码:
df['E'] = df['B'].str.translate(None, ",!.; -@!%^&*)(")
Run Code Online (Sandbox Code Playgroud)
它只有在我知道什么是特殊字符时才有用.
但我想使用re哪种方式最好.
import re
#re.sub(r'\W+', '', your_string)
df['E'] = re.sub(r'\W+', '', df['B'].str) …Run Code Online (Sandbox Code Playgroud) 使用nltk时,标点符号和数字小写不起作用.
我的代码
stopwords=nltk.corpus.stopwords.words('english')+ list(string.punctuation)
user_defined_stop_words=['st','rd','hong','kong']
new_stop_words=stopwords+user_defined_stop_words
def preprocess(text):
return [word for word in word_tokenize(text) if word.lower() not in new_stop_words and not word.isdigit()]
miss_data['Clean_addr'] = miss_data['Adj_Addr'].apply(preprocess)
Run Code Online (Sandbox Code Playgroud)
样本输入
23FLOOR 9 DES VOEUX RD WEST HONG KONG
PAG CONSULTING FLAT 15 AIA CENTRAL 1 CONNAUGHT RD CENTRAL
C/O CITY LOST STUDIOS AND FLAT 4F 13-15 HILLIER ST SHEUNG HONG KONG
Run Code Online (Sandbox Code Playgroud)
预期产出
floor des voeux west
pag consulting flat aia central connaught central
co city lost studios flat f hillier sheung
Run Code Online (Sandbox Code Playgroud) 我是python的新手,所以这可能是一个非常基本的问题.我正在尝试使用lambda来删除pandas数据帧中每一行的标点符号.我使用了以下内容,但收到了错误.我试图避免将df转换为列表然后将清理后的结果附加到新列表中,然后将其转换回df.
任何建议,将不胜感激!
import string
df['cleaned'] = df['old'].apply(lambda x: x.replace(c,'') for c in string.punctuation)
Run Code Online (Sandbox Code Playgroud) 使用Canopy和Pandas,我有数据框a,其定义如下:
a=pd.read_csv('text.txt')
df=pd.DataFrame(a)
df.columns=["test"]
Run Code Online (Sandbox Code Playgroud)
test.txt是一个单列文件,包含一个包含文本,数字和标点符号的字符串列表.
假设df看起来像:
测试
%HGH&12
ABC123!
porkyfries
我希望我的结果是:
测试
hgh12
ABC123
porkyfries
到目前为止的努力:
from string import punctuation /-- import punctuation list from python itself
a=pd.read_csv('text.txt')
df=pd.DataFrame(a)
df.columns=["test"] /-- define the dataframe
for p in list(punctuation):
...: df2=df.med.str.replace(p,'')
...: df2=pd.DataFrame(df2);
...: df2
Run Code Online (Sandbox Code Playgroud)
上面的命令基本上只返回我相同的数据集.感谢任何线索.
编辑:我使用Pandas的原因是因为数据很大,跨越了大约1M行,未来编码的使用将应用于最多30M行的列表.简而言之,我需要以非常有效的方式为大数据集清理数据.
我试图从现有的 DataFrame 中获取一个 DataFrame ,该数据帧仅包含特定列(其值为字符串)中的值不包含特定字符的行。
即如果我们不想要的字符是 '('
原始数据框:
some_col my_column
0 1 some
1 2 word
2 3 hello(
Run Code Online (Sandbox Code Playgroud)
新数据框:
some_col my_column
0 1 some
1 2 word
Run Code Online (Sandbox Code Playgroud)
我试过df.loc['(' not in df['my_column']],但这不起作用,因为它df['my_column']是一个 Series 对象。
我也试过:df.loc[not df.my_column.str.contains('(')],这也不起作用。
我有大于100列的数据框.我想选择0~32和#83列.看起来1切片可以正常使用下面的代码.
df_new = df[df.columns[0:32]]
Run Code Online (Sandbox Code Playgroud)
但它不适用于下面的2个切片代码.我该如何解决这个问题?
df_new = df[df.columns[0:32, 83]]
Run Code Online (Sandbox Code Playgroud) 我有数据帧(熊猫):
data1 = pandas.DataFrame(['??????, ????', '??? ?????', '????!!'])
Run Code Online (Sandbox Code Playgroud)
如您所见,它包含 unicode 符号(西里尔文):
>>> data1
0
0 ??????, ????
1 ??? ?????
2 ????!!
Run Code Online (Sandbox Code Playgroud)
我尝试从数据框列中删除所有特定符号。 我试过:
data1.apply(replace ???)
data1[0].replace()
Run Code Online (Sandbox Code Playgroud)
甚至还有 lambda 的东西。但我不知道如何replace正确调用。所以我想显示所有符号必须按范围删除:
x in '!@#$%^&*()'
Run Code Online (Sandbox Code Playgroud)
或者
if chr(x) not in range(1040,1072) # chr() of cyrillic
Run Code Online (Sandbox Code Playgroud) 我有一个如下所示的数据框:
index value
0 1
1 1
2 2
3 3
4 2
5 1
6 1
Run Code Online (Sandbox Code Playgroud)
我想要的是每个值返回前一个较小值的索引,此外,还有前一个"1"值的索引.如果值为1,我不需要它们(两个值都可以是-1或者某个值).
所以我要追求的是:
index value previous_smaller_index previous_1_index
0 1 -1 -1
1 1 -1 -1
2 2 1 1
3 3 2 1
4 2 1 1
5 1 -1 -1
6 1 -1 -1
Run Code Online (Sandbox Code Playgroud)
我尝试使用滚动,累积功能等但我无法弄明白.任何帮助,将不胜感激!
编辑:SpghttCd已经为"之前的1"问题提供了一个很好的解决方案.我正在为"前一个小问题"找一个漂亮的熊猫一个班轮.(尽管如此,对于这两个问题,欢迎使用更好,更有效的解决方案)