pandas where mask函数详解,get操作DataFrame的正确姿势

Pandas是Python数据科学生态中重要的基础成员,功能强大,用法灵活,简单记录之。更佳阅读体验可移步 Pandas核心概述

这里重点介绍pandas的where mask函数,如果能从这两个函数的用法get到pandas的精髓就再好不过了。

用法说明,官方的用法说明比较简洁:
where :替换条件(condition)为Flase处的值
mask :替换条件(condition)为True处的值

where(self, cond, other=nan, inplace=False,
	  axis=None, level=None, errors='' raise', try_cast=False)
	  
mask(self, cond, other=nan, inplace=False,
	  axis=None, level=None, errors='' raise', try_cast=False)

当然,这里的condition 自然就是参数列表中的 cond,既然是替换值。
那么替换后的值是什么呢,就是参数列表中的other ,方法还为other指定了默认值None。

下面先用pandas中的Series对象测试一下:

#定义一个Series
s = pd.Series(range(5))
s
0    0
1    1
2    2
3    3
4    4
dtype: int64

#执行where函数
s.where(s > 2,"我的自定义")
0    我的自定义
1    我的自定义
2    我的自定义
3        3
4        4
dtype: object
#符合条件的显示原来的数据,不符合条件的显示 **other**参数给定的值

#执行mask函数
s.mask(s > 2,"我的自定义")
0        0
1        1
2        2
3    我的自定义
4    我的自定义
dtype: object
#符合条件的显示 **other**参数给定的值,不符合条件的显示原来的数据

上面解释说参数 cond传入布尔值,那么我们来看下s>2,究竟是什么东西

s > 2
0    False
1    False
2    False
3     True
4     True
dtype: bool

以上的操作已经很容易看懂这俩函数的用法,好像这俩函数就是一个相反的函数,在条件一致的情况下得到的结果是相反的,也就是说如果定义m=s>2, 以下两个函数的结果应该是相同的。

m=s>2
s.where(m,"我的自定义")
s.mask(~m ,"我的自定义")

于是以下会得到一组布尔值

s.where(m,"我的自定义")==s.mask(~m ,"我的自定义")
0    True
1    True
2    True
3    True
4    True
dtype: bool

上面我们仅仅是用了自己定义的一个数,如果我们用一组数呢

s.where(s > 2,  pd.Series(range(10,15)))
0    10
1    11
2    12
3     3
4     4
dtype: int64

也成功的替换成了给定Series对应下标的值

那么我们猜测他就是按照下标去对应值,我们换一个长度不一致的Series呢

s.where(s > 2,  pd.Series(range(10,300)))

#结果和上面一致

下面用DataFrame进行测试,验证一下就好了

df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
df
	A	B
0	0	1
1	2	3
2	4	5
3	6	7
4	8	9

测试函数:
条件是 DF中的元素被3除尽 根据函数要求返回-df中的相应值

m=df % 3 == 0
m
 	 A	       B
0	True	False
1	False	True
2	False	False
3	True	False
4	False	True

#where : 不满足条件返回other
df.where(m, -df)
A	B
0	0	-1
1	-2	-3
2	-4	-5
3	6	7
4	8	9

#mask : 满足条件返回other
df.mask(m,-df)
	A	B
0	0	1
1	2	3
2	4	5
3	-6	-7
4	-8	-9

df.where(m, -df) == df.mask(~m, -df)
A	B
0	True	True
1	True	True
2	True	True
3	True	True
4	True	True

官方文中还讲了numpy中另外一个函数的用法与这俩相同

np.where(m, df, -df)
array([[ 0, -1],
       [-2,  3],
       [-4, -5],
       [ 6, -7],
       [-8,  9]])
#输出上好像格式不太一样

df.where(m, -df) == np.where(m, df, -df)
A	B
0	True	True
1	True	True
2	True	True
3	True	True
4	True	True

也能说明pandas和numpy的关系,pansdas是基于Numpy的一种工具

df.where()   
df.mask()  
np.where()  

以上三个函数
上面我们也看到DF的操作其实是非常随心所欲的一个“-df”就把里面所有的元素都取相反数了,一个比较运算符(如 df>2)就可以取所有元素运算的布尔结果,感觉excel是不是弱爆了。

可能会有些啰嗦,但我觉得这样展示出来,可能才会有点收获😂

``` from bertopic import BERTopic import numpy as np import pandas as pd from umap import UMAP from hdbscan import HDBSCAN from sklearn.feature_extraction.text import CountVectorizer from bertopic.vectorizers import ClassTfidfTransformer import re import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from nltk.tokenize import word_tokenize from wordcloud import WordCloud import matplotlib.pyplot as plt # 加载原始文本数据(仍需用于主题表示) df = pd.read_csv('tokenized_abstract.csv', encoding='utf-8') sentences = df['Tokenized_Abstract'].tolist() print('文本条数: ', len(sentences)) print('预览第一条: ', sentences[0]) # 检查缺失值 print("缺失值数量:", df['Tokenized_Abstract'].isna().sum()) # 检查非字符串类型 non_str_mask = df['Tokenized_Abstract'].apply(lambda x: not isinstance(x, str)) print("非字符串样本:\n", df[non_str_mask]['Tokenized_Abstract'].head()) vectorizer_model = None from sentence_transformers import SentenceTransformer # Step 1 - Extract embeddings embedding_model = SentenceTransformer("C:\\Users\\18267\\.cache\\huggingface\\hub\\models--sentence-transformers--all-mpnet-base-v2\\snapshots\\9a3225965996d404b775526de6dbfe85d3368642") embeddings = np.load('clean_emb_last.npy') print(f"嵌入的形状: {embeddings.shape}") # Step 2 - Reduce dimensionality umap_model = UMAP(n_neighbors=7, n_components=10, min_dist=0.0, metric='cosine',random_state=42) # Step 3 - Cluster reduced embeddings hdbscan_model = HDBSCAN(min_samples=7, min_cluster_size=60,metric='euclidean', cluster_selection_method='eom', prediction_data=True) # Step 4 - Tokenize topics # Combine custom stop words with scikit-learn's English stop words custom_stop_words = ['h2', 'storing', 'storage', 'include', 'comprise', 'utility', 'model', 'disclosed', 'embodiment', 'invention', 'prior', 'art', 'according', 'present', 'method', 'system', 'device', 'may', 'also', 'use', 'used', 'provide', 'wherein', 'configured', 'predetermined', 'plurality', 'comprising', 'consists', 'following', 'characterized', 'claim', 'claims', 'said', 'first', 'second', 'third', 'fourth', 'fifth', 'one', 'two', 'three','hydrogen'] # Create combined stop words set all_stop_words = set(custom_stop_words).union(ENGLISH_STOP_WORDS) vectorizer_model = CountVectorizer(stop_words=list(all_stop_words)) # Step 5 - Create topic representation ctfidf_model = ClassTfidfTransformer() # All steps together topic_model = BERTopic( embedding_model=embedding_model, # Step 1 - Extract embeddings umap_model=umap_model, # Step 2 - Reduce dimensionality hdbscan_model=hdbscan_model, # Step 3 - Cluster reduced embeddings vectorizer_model=vectorizer_model, # Step 4 - Tokenize topics ctfidf_model=ctfidf_model, # Step 5 - Extract topic words top_n_words=50 ) # 拟合模型 topics, probs = topic_model.fit_transform(documents=sentences, # 仍需提供文档用于主题词生成 embeddings=embeddings # 注入预计算嵌入) ) # 获取主题聚类信息 topic_info = topic_model.get_topic_info() print(topic_info)```现在如果嵌入、降维、聚类等步骤与先前保持一致,仅在主题表示步骤对 c-TF-IDF 算法进行调整实现,为每个阶段的摘要文本分配时间戳,调整逆 文档频率计算方式,并取词频的平方根,适当减小常用词的分数,C-TF-IDF的计算方式调整为: $ c-TF-IDF_{w,c,r} = \frac{\left(\sqrt{\frac{f_{w,c,r}}{f_c}} + \sqrt{\frac{f_{w,c,r-1}}{f_c}}\right) \cdot \log\left(1 + \frac{M - cf_w + 0.5}{cf_w + 0.5}\right)}{2} $ 文字说明: “其中,( f_{w,c,r} ) 为第 ( r ) 阶段时,词 ( w ) 在聚类簇 ( c ) 中出现的频次,( f_c ) 表示聚类簇 ( c ) 中词数。( M ) 表示簇的平均单词数,( cf_w ) 表示词 ( w ) 在所有簇中出现频次。” 请给出修改后的代码
03-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值