You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python基于用户输入构建施药设备按日除草剂用量表格

按施药设备和日期分类的除草剂用量表格实现方案

需求说明

已有包含DeviceName(施药设备名)和DAY(当月日期)字段的pandas DataFrame,已通过以下代码提取唯一设备和日期:

devices = df['DeviceName'].unique()
days = df['DAY'].unique()

通过嵌套循环收集了各设备每日的除草剂用量输入,存储在herbicides列表中,需要将这些数据整理成如下格式的表格:

DeviceName          24       25       26       27       28
Applied_AA-19     Input #  Input #  Input #  Input #  Input #
Applied_AA-24     Input #  Input #  Input #  Input #  Input #

实现步骤

1. 转换输入数据结构

herbicides列表是按「设备1-日期1、设备1-日期2…设备2-日期1、设备2-日期2…」的顺序存储的,先把它拆分成对应每个设备的子列表:

# 拆分列表,每个子列表对应一个设备的所有日期用量
herbicide_rows = [herbicides[i*len(days):(i+1)*len(days)] for i in range(len(devices))]

2. 创建目标格式的DataFrame

以设备名为索引,日期为表头,用量为对应值,最后把索引转为DeviceName列:

import pandas as pd

# 构建初始DataFrame
result_df = pd.DataFrame(herbicide_rows, index=devices, columns=days)
# 将索引转为DeviceName列
result_df.reset_index(inplace=True)
result_df.rename(columns={'index': 'DeviceName'}, inplace=True)

3. 格式化输出表格

用to_string()方法可以输出和示例格式一致的文本表格:

print(result_df.to_string(index=False))

完整代码示例

import pandas as pd

# 模拟示例DataFrame(实际使用时替换为你的真实数据)
data = {'DeviceName': ['Applied_AA-19', 'Applied_AA-19', 'Applied_AA-24', 'Applied_AA-24'],
        'DAY': [24,25,24,25]}
df = pd.DataFrame(data)

devices = df['DeviceName'].unique()
days = df['DAY'].unique()

# 收集用户输入
herbicides = []
for device in devices:
    for day in days:
        herbicide = input(f"请输入设备{device}在{day}日的除草剂用量:")
        herbicides.append(herbicide)

# 转换数据并生成表格
herbicide_rows = [herbicides[i*len(days):(i+1)*len(days)] for i in range(len(devices))]
result_df = pd.DataFrame(herbicide_rows, index=devices, columns=days)
result_df.reset_index(inplace=True)
result_df.rename(columns={'index': 'DeviceName'}, inplace=True)

# 输出最终表格
print(result_df.to_string(index=False))

内容的提问来源于stack exchange,提问作者Luis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:27:53