将函数应用于 pandas 数据框:是否有更有效的方法?
Applying function to pandas dataframe: is there a more efficient way of doing this?
我有一个数据框,它的列数很少但行数很多(现在大约 900K,随着我收集更多数据,它会变得更大)。它看起来像这样:
Author
Title
Date
Category
Text
url
0
Amira Charfeddine
Wild Fadhila 01
2019-01-01
novel
الكتاب هذا نهديه لكل تونسي حس إلي الكتاب يحكي ...
NaN
1
Amira Charfeddine
Wild Fadhila 02
2019-01-01
novel
في التزغريت، والعياط و الزمامر، ليوم نتيجة الب...
NaN
2
253826
1515368_7636953
2010-12-28
/forums/forums/91/
هذا ما ينص عليه إدوستور التونسي لا رئاسة مدى ا...
https://www.tunisia-sat.com/forums/threads/151...
3
250442
1504416_7580403
2010-12-21
/forums/sports/
\n\n\n\n\n\nاعلنت الجامعة التونسية لكرة اليد ا...
https://www.tunisia-sat.com/forums/threads/150...
4
312628
1504416_7580433
2010-12-21
/forums/sports/
quel est le résultat final\n,,,,????
https://www.tunisia-sat.com/forums/threads/150...
“文本”栏有一串文本,可能只有几个字(在论坛 post 的情况下),也可能是小说的一部分,有数万字(如上面的前两行)。
我有代码从各种语料库文件(.txt 和 .json)构造数据框,然后清理文本并将清理后的数据框保存为 pickle 文件。
我正在尝试 运行 下面的代码来分析语料库中不同单词的拼写变化有多大。这些函数看起来很简单:计算每个文本行中特定拼写变量的出现次数;另一个获取此类频率的列表并为每个引理计算基尼系数(这只是拼写异质性的数值度量)。它引用了一个 spelling_var 字典,该字典以一个词条作为其键,并将该词条的各种拼写方式作为值。 (如 {'color': ['color', 'colour']} 除了不是英文。)
此代码有效,但它使用了很多 CPU 时间。我不确定有多少,但我使用 PythonAnywhere 进行编码,这段代码让我进入了 tarpit(换句话说,它让我超过了我每天允许的 CPU 秒)。
有没有一种方法可以减少 CPU 强度?最好不需要我学习另一个包(过去几周我一直在学习 Pandas 并且很喜欢它,只需要继续我的分析)。一旦我有了代码并完成了语料库的收集,我只会 运行 几次;我不会 运行 每天或任何事情(以防万一)。
代码如下:
import pickle
import pandas as pd
import re
with open('1_raw_df.pkl', 'rb') as pickle_file:
df = pickle.load(pickle_file)
spelling_var = {
'illi': ["الي", "اللي"],
'besh': ["باش", "بش"],
...
}
spelling_df = df.copy()
def count_word(df, word):
pattern = r"\b" + re.escape(word) + r"\b"
return df['Text'].str.count(pattern)
def compute_gini(freq_list):
proportions = [f/sum(freq_list) for f in freq_list]
squared = [p**2 for p in proportions]
return 1-sum(squared)
for w, var in spelling_var.items():
count_list = []
for v in var:
count_list.append(count_word(spelling_df, v))
gini = compute_gini(count_list)
spelling_df[w] = gini
我在最后一个双循环中重写了两行,见下面代码中的注释。这能解决您的问题吗?
gini_lst = []
for w, var in spelling_var.items():
count_list = []
for v in var:
count_list.append(count_word(spelling_df, v))
#gini = compute_gini(count_list) # don't think you need to compute this at every iteration of the inner loop, right?
#spelling_df[w] = gini # having this inside of the loop creates a new column at each iteration, which could crash your CPU
gini_lst.append(compute_gini(count_list))
# this creates a df with a row for each lemma with its associated gini value
df_lemma_gini = pd.DataFrame(data={"lemma_column": list(spelling_var.keys()), "gini_column": gini_lst})
我有一个数据框,它的列数很少但行数很多(现在大约 900K,随着我收集更多数据,它会变得更大)。它看起来像这样:
Author | Title | Date | Category | Text | url | |
---|---|---|---|---|---|---|
0 | Amira Charfeddine | Wild Fadhila 01 | 2019-01-01 | novel | الكتاب هذا نهديه لكل تونسي حس إلي الكتاب يحكي ... | NaN |
1 | Amira Charfeddine | Wild Fadhila 02 | 2019-01-01 | novel | في التزغريت، والعياط و الزمامر، ليوم نتيجة الب... | NaN |
2 | 253826 | 1515368_7636953 | 2010-12-28 | /forums/forums/91/ | هذا ما ينص عليه إدوستور التونسي لا رئاسة مدى ا... | https://www.tunisia-sat.com/forums/threads/151... |
3 | 250442 | 1504416_7580403 | 2010-12-21 | /forums/sports/ | \n\n\n\n\n\nاعلنت الجامعة التونسية لكرة اليد ا... | https://www.tunisia-sat.com/forums/threads/150... |
4 | 312628 | 1504416_7580433 | 2010-12-21 | /forums/sports/ | quel est le résultat final\n,,,,???? | https://www.tunisia-sat.com/forums/threads/150... |
“文本”栏有一串文本,可能只有几个字(在论坛 post 的情况下),也可能是小说的一部分,有数万字(如上面的前两行)。
我有代码从各种语料库文件(.txt 和 .json)构造数据框,然后清理文本并将清理后的数据框保存为 pickle 文件。
我正在尝试 运行 下面的代码来分析语料库中不同单词的拼写变化有多大。这些函数看起来很简单:计算每个文本行中特定拼写变量的出现次数;另一个获取此类频率的列表并为每个引理计算基尼系数(这只是拼写异质性的数值度量)。它引用了一个 spelling_var 字典,该字典以一个词条作为其键,并将该词条的各种拼写方式作为值。 (如 {'color': ['color', 'colour']} 除了不是英文。)
此代码有效,但它使用了很多 CPU 时间。我不确定有多少,但我使用 PythonAnywhere 进行编码,这段代码让我进入了 tarpit(换句话说,它让我超过了我每天允许的 CPU 秒)。
有没有一种方法可以减少 CPU 强度?最好不需要我学习另一个包(过去几周我一直在学习 Pandas 并且很喜欢它,只需要继续我的分析)。一旦我有了代码并完成了语料库的收集,我只会 运行 几次;我不会 运行 每天或任何事情(以防万一)。
代码如下:
import pickle
import pandas as pd
import re
with open('1_raw_df.pkl', 'rb') as pickle_file:
df = pickle.load(pickle_file)
spelling_var = {
'illi': ["الي", "اللي"],
'besh': ["باش", "بش"],
...
}
spelling_df = df.copy()
def count_word(df, word):
pattern = r"\b" + re.escape(word) + r"\b"
return df['Text'].str.count(pattern)
def compute_gini(freq_list):
proportions = [f/sum(freq_list) for f in freq_list]
squared = [p**2 for p in proportions]
return 1-sum(squared)
for w, var in spelling_var.items():
count_list = []
for v in var:
count_list.append(count_word(spelling_df, v))
gini = compute_gini(count_list)
spelling_df[w] = gini
我在最后一个双循环中重写了两行,见下面代码中的注释。这能解决您的问题吗?
gini_lst = []
for w, var in spelling_var.items():
count_list = []
for v in var:
count_list.append(count_word(spelling_df, v))
#gini = compute_gini(count_list) # don't think you need to compute this at every iteration of the inner loop, right?
#spelling_df[w] = gini # having this inside of the loop creates a new column at each iteration, which could crash your CPU
gini_lst.append(compute_gini(count_list))
# this creates a df with a row for each lemma with its associated gini value
df_lemma_gini = pd.DataFrame(data={"lemma_column": list(spelling_var.keys()), "gini_column": gini_lst})