用python把excel不同不同字数的文章分类,并统计数量

import pandas as pd

# 读取Excel文件
df = pd.read_csv(r'C:\Users\win10\Documents\WXWork\1688855780474743\Cache\File\2023-03\us_thinktank_art.csv')

# 创建一个空的DataFrame来保存结果
result_df = pd.DataFrame(columns=['think_tank_name', 'word_count_range', 'count'])

# 定义篇幅范围
ranges = [(0, 500), (501, 1000), (1001, 1500), (2001, float('inf'))]

# 对每个智库和篇幅分类计数
for think_tank_name in df['think_tank_name'].unique():
    for word_count_range in ranges:
        count = ((df['think_tank_name'] == think_tank_name) & 
                 (df['art_content'].str.len().between(word_count_range[0], word_count_range[1])) &
                 (df['art_content'].str.len() >= 50)).sum()
        result_df = result_df.append({'think_tank_name': think_tank_name,
                                      'word_count_range': f"{word_count_range[0]}-{word_count_range[1]}",
                                      'count': count},
                                     ignore_index=True)

# 将结果写入新的Excel文件
result_df.to_csv(r'C:\Users\win10\Documents\WXWork\1688855780474743\Cache\File\2023-03\us_thinktank_art.csv', index=False)

import pandas as pd

# 读取Excel文件
df = pd.read_csv(r'C:\Users\win10\Documents\WXWork\1688855780474743\Cache\File\2023-03\us_thinktank_art.csv')

# 使用groupby方法进行分组统计
result_df = df.groupby(['think_tank_name', 'art_type']).size().reset_index(name='count')

# 将结果写入新的Excel文件
result_df.to_excel(r'C:\Users\win10\Desktop\abc.xlsx', index=False)

你可能感兴趣的:(pandas,python,数据分析)