![](/img/trans.png)
[英]How to rename a pandas dataframe in a memory-efficient way (without creating a copy)?
[英]Applying function to pandas dataframe: is there a more memory-efficient way of doing this?
我有一个数据框,它有少量列但有很多行(现在大约 900K,随着我收集更多数据,它会变得更大)。 它看起来像这样:
作者 | 标题 | 日期 | 类别 | 文本 | 网址 | |
---|---|---|---|---|---|---|
0 | 阿米拉·查菲丁 | 野生法迪拉 01 | 2019-01-01 | 小说 | الكتاب هذا نهديه لكل تونسي حس إلي الكتاب يحكي ... | NaN |
1 | 阿米拉·查菲丁 | 野生法迪拉 02 | 2019-01-01 | 小说 | في التزغريت، والعياط و الزمامر، ليوم نتيجة الب... | NaN |
2 | 253826 | 1515368_7636953 | 2010-12-28 | /论坛/论坛/91/ | هذا ما ينص عليه إدوستور التونسي لا رئاسة مدى ا... | https://www.tunisia-sat.com/forums/threads/151.. |
3 | 250442 | 1504416_7580403 | 2010-12-21 | /论坛/体育/ | \\n\\n\\n\\n\\n\\nاعلنت الجامعة التونسية لكرة اليد ا... | https://www.tunisia-sat.com/forums/threads/150.. |
4 | 312628 | 1504416_7580433 | 2010-12-21 | /论坛/体育/ | quel est le résultat final\\n,,,,???? | https://www.tunisia-sat.com/forums/threads/150.. |
“文本”栏包含一串文本,可能只有几个字(在论坛帖子的情况下),也可能是小说的一部分,有数万个字(如上面的前两行) .
我有从各种语料库文件(.txt 和 .json)构建数据框的代码,然后清理文本并将清理后的数据框保存为 pickle 文件。
我正在尝试运行以下代码来分析不同单词的拼写在语料库中的变化程度。 这些函数看起来很简单:计算每个 Text 行中特定拼写变量的出现次数; 另一个获取此类频率的列表并计算每个引理的基尼系数(这只是拼写异质性的数字度量)。 它引用了一个以引理为键的拼写_var 字典,以及将该引理作为值的各种拼写方法。 (类似于 {'color': ['color', 'colour']} 除非不是英文。)
此代码有效,但它使用了大量内存。 我不确定多少,但我使用 PythonAnywhere 进行编码,这段代码将我送入了tarpit(换句话说,它使我超过了每天的 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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.