如何以最有效的方式在DataFramePython中为列添加值?
我有一个数据框如何以最有效的方式在DataFramePython中为列添加值?,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个数据框df,由两列组成(单词和该单词的含义/定义)。我想为每个单词的定义使用集合。Counter对象,并尽可能以最简洁的方式计算单词在定义中出现的频率 传统的方法是使用iterrows()方法迭代数据帧并进行计算 样本输出 单词 意思 词频 排列 同构数据类型的集合 {'collection':1,'of':1..} 假设df有两列'word'和'definition',那么在空间上拆分后,只需使用.map方法和definition序列上的计数器。然后对结果求和 from colle
df
,由两列组成(单词和该单词的含义/定义)。我想为每个单词的定义使用集合。Counter
对象,并尽可能以最简洁的方式计算单词在定义中出现的频率
传统的方法是使用iterrows()
方法迭代数据帧并进行计算
样本输出
单词
意思
词频
排列
同构数据类型的集合
{'collection':1,'of':1..}
假设df
有两列'word'
和'definition'
,那么在空间上拆分后,只需使用.map
方法和definition
序列上的计数器。然后对结果求和
from collections import Counter
def_counts = df.definition.map(lambda x: Counter(x.split()))
all_counts = def_counts.sum()
我会利用Pandasstr
accessor方法来实现这一点
from collections import Counter
Counter(df.definition.str.cat(sep=' ').split())
一些测试数据
df = pd.DataFrame({'word': ['some', 'words', 'yes'], 'definition': ['this is a definition', 'another definition', 'one final definition']})
print(df)
definition word
0 this is a definition some
1 another definition words
2 one final definition yes
然后使用计数器按空间进行连接和拆分
Counter(df.definition.str.cat(sep=' ').split())
Counter({'a': 1,
'another': 1,
'definition': 3,
'final': 1,
'is': 1,
'one': 1,
'this': 1})
我希望这个答案是有用的,但不是选择的答案。事实上,我只是在为计数器和@TedPetrou的答案辩护
创建随机单词的大型示例
a = np.random.choice(list(ascii_lowercase), size=(100000, 5))
definitions = pd.Series(
pd.DataFrame(a).sum(1).values.reshape(-1, 10).tolist()).str.join(' ')
definitions.head()
0 hmwnp okuat sexzr jsxhh bdoyc kdbas nkoov moek...
1 iiuot qnlgs xrmss jfwvw pmogp vkrvl bygit qqon...
2 ftcap ihuto ldxwo bvvch zuwpp bdagx okhtt lqmy...
3 uwmcs nhmxa qeomd ptlbg kggxr hpclc kwnix rlon...
4 npncx lnors gyomb dllsv hyayw xdynr ctwvh nsib...
dtype: object
定时
计数器
比我能想到的最快速度快1000倍
Ted Petrou:谢谢你的评论。我还想知道如何以最简单的方式对1000个单词的定义进行类似的计算?这适用于所有不同单词大小的大量定义我的意思是对1000个不同的单词,即数据帧中的1000行进行类似的计算?谢谢James。。你的建议帮了大忙