Skip to main content
 首页 » 编程设计

python之将整数存储为整数而不是 float

2024年11月24日8JeffreyZhao

我做了以下事情:

import pandas as pd 
 
df_texts = pd.read_csv('data_texts.csv', keep_default_na=True) 
 
for index, row in df_texts.iterrows():    
 
    list_of_words = row['text'].split() 
 
    df_texts.loc[index, '#_words'] = len(list_of_words) 
 
    list_of_unique_words = set(list_of_words)   
 
    df_texts.loc[index, '#_unique_words'] = len(list_of_unique_words) 

问题是 #_words 和 #_unique_words 列中的数字存储为 float ,即使它们是整数。

只是为了澄清这两列并不预先存在于我读取的 .csv (pd.read_csv) 中,而是我在 for 循环中创建它们。

如何直接将它们存储为整数?

请您参考如下方法:

执行此操作并直接获取整数的更好方法是直接分配新列,并避免完全遍历数据帧。

以一些虚拟数据为例:

import pandas as pd 
texts = ['word1 word2 word3', 'word1 word2 word1', 'word3'] 
 
df_texts = pd.DataFrame(texts, columns = ['text']) 
                text 
0  word1 word2 word3 
1  word1 word2 word1 
2              word3 

分别使用文本列计算所有行的长度,然后分配。

temp = df_texts['text'].str.split() 
df_texts['#_words'] = [len(row) for row in temp] #iterates and creates a list of all lengths. assign to df 
df_texts['#_unique_words'] = [len(set(row)) for row in temp] 
 
print(df_texts) 
#Output: 
                text  #_words  #_unique_words 
0  word1 word2 word3        3               3 
1  word1 word2 word1        3               2 
2              word3        1               1