Python代码优化:处理Excel数据中智能化字段的跨行内容

本文将介绍如何使用Python代码处理Excel数据中智能化字段的跨行内容,具体来说是将下一行非空智能化内容作为当前行智能化内容,并使用pandas库进行数据读取和操作。

原始代码:

import pandas as pd

# 读取Excel文件
df = pd.read_excel('C:\Users\86186\Desktop\汽车之家_秦plus_评论.xls')

# 初始化字典列表
sentences = []

# 遍历每一行数据
for index, row in df.iterrows():
    if pd.notnull(row['用户昵称']) and pd.notnull(row['最满意']):
        sentence_dict = {}
        columns = df.columns.tolist()
        start_index = columns.index('最满意')
        for column in columns[start_index:]:
            if column == '智能化' and pd.notnull(df.iloc[index+1]['智能化']):
                sentence_dict[column] = [sentence.strip() for sentence in str(df.iloc[index+1][column]).split(',')]
            else:
                sentence_dict[column] = [sentence.strip() for sentence in str(row[column]).split(',')]
        sentences.append(sentence_dict)

# 打印结果
for sentence_dict in sentences:
    print(sentence_dict)

代码说明:

  1. 代码首先使用pandas库读取Excel文件,并将数据存储在df变量中。
  2. 然后初始化一个空列表sentences,用于存储处理后的数据。
  3. 代码使用循环遍历Excel文件中的每一行数据,并判断'用户昵称'和'最满意'列是否为空。
  4. 如果两列都不为空,则创建一个字典sentence_dict,并将从'最满意'列开始的所有列的内容添加到字典中。
  5. 代码添加了一个条件判断语句:如果当前行的'智能化'列为空,但下一行的'智能化'列非空,则将下一行的'智能化'内容作为当前行的'智能化'内容。
  6. 最后,将处理后的字典添加到sentences列表中,并打印结果。

优化后的代码:

import pandas as pd

# 读取Excel文件
df = pd.read_excel('C:\Users\86186\Desktop\汽车之家_秦plus_评论.xls')

# 初始化字典列表
sentences = []

# 遍历每一行数据
for index, row in df.iterrows():
    if pd.notnull(row['用户昵称']) and pd.notnull(row['最满意']):
        sentence_dict = {}
        columns = df.columns.tolist()
        start_index = columns.index('最满意')
        for column in columns[start_index:]:
            if column == '智能化' and pd.isnull(row['智能化']) and pd.notnull(df.iloc[index+1]['智能化']):
                sentence_dict[column] = [sentence.strip() for sentence in str(df.iloc[index+1][column]).split(',')]
            else:
                sentence_dict[column] = [sentence.strip() for sentence in str(row[column]).split(',')]
        sentences.append(sentence_dict)

# 打印结果
for sentence_dict in sentences:
    print(sentence_dict)

代码修改:

  1. 在处理'智能化'列时,添加了对当前行'智能化'列是否为空的判断。
  2. 如果当前行'智能化'列为空,且下一行'智能化'列非空,则将下一行的'智能化'内容作为当前行的'智能化'内容。

代码使用说明:

  1. 请确保你已经安装了pandas库和xlrd库。
  2. 将代码中的文件路径修改为你的实际路径。
  3. 运行代码即可将Excel数据处理并打印结果。

注意:

  1. 该代码只处理了'智能化'列的跨行内容,其他列的处理方式保持不变。
  2. 代码假设'智能化'列的跨行内容只出现在相邻的两行之间。
  3. 代码使用pd.isnull函数判断当前行'智能化'列是否为空。

希望本文对你有所帮助! 如果还有其他问题,欢迎留言讨论。

Python代码优化:处理Excel数据中智能化字段的跨行内容

原文地址: https://www.cveoy.top/t/topic/Skr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录