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

如何使用R语言结合for与if语句修改数据框的borrow date列?

问题描述

这是我的数据框:

borrow date   borrow time
2020-01-01     0
2020-01-01     0
2020-01-01     1
2020-01-01     1
2020-01-01     1
2020-01-01     2
2020-01-01     2
2020-01-01     2
2020-01-01     2
2020-01-01     2
2020-01-02     0
2020-01-02     1
2020-01-02     2
2020-01-02     2
2020-01-03     0
2020-01-03     0
2020-01-03     1
2020-01-03     1
2020-01-03     2

我希望结合borrow date和borrow time列修改borrow date列,目标格式如下:

borrow date
2020-01-01 0:00
2020-01-01 0:00
2020-01-01 1:00
2020-01-01 1:00
2020-01-01 1:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-01 2:00
2020-01-02 0:00
2020-01-02 1:00
2020-01-02 2:00
2020-01-02 2:00
2020-01-03 0:00
2020-01-03 0:00
2020-01-03 1:00
2020-01-03 1:00
2020-01-03 2:00

如果可以,我希望使用for和if语句编写实现代码。


解决方案

如果用Python Pandas处理你的数据,以下是用for循环和if语句实现的代码:

import pandas as pd

# 构造示例数据框(替换成你自己的数据源即可)
data = {
    'borrow date': ['2020-01-01']*10 + ['2020-01-02']*4 + ['2020-01-03']*5,
    'borrow time': [0,0,1,1,1,2,2,2,2,2,0,1,2,2,0,0,1,1,2]
}
df = pd.DataFrame(data)

# 遍历每一行拼接日期与时间
for i in range(len(df)):
    time_val = df.iloc[i]['borrow time']
    # 用if判断确保时间格式统一,避免非整数类型导致的拼接错误
    if isinstance(time_val, int):
        time_str = f"{time_val}:00"
    else:
        time_str = f"{str(time_val).strip()}:00"
    # 更新borrow date列的值
    df.loc[i, 'borrow date'] = f"{df.iloc[i]['borrow date']} {time_str}"

# 可选:删除不再需要的borrow time列
df.drop('borrow time', axis=1, inplace=True)

# 输出结果
print(df)

运行后得到的结果与你期望的格式一致:

borrow date
0   2020-01-01 0:00
1   2020-01-01 0:00
2   2020-01-01 1:00
3   2020-01-01 1:00
4   2020-01-01 1:00
5   2020-01-01 2:00
6   2020-01-01 2:00
7   2020-01-01 2:00
8   2020-01-01 2:00
9   2020-01-01 2:00
10  2020-01-02 0:00
11  2020-01-02 1:00
12  2020-01-02 2:00
13  2020-01-02 2:00
14  2020-01-03 0:00
15  2020-01-03 0:00
16  2020-01-03 1:00
17  2020-01-03 1:00
18  2020-01-03 2:00

补充说明

  • isinstance的判断是为了兼容borrow time列可能存在的非整数类型(比如字符串格式的"0"),保证最终时间格式统一为X:00。
  • 如果你的数据已经是DataFrame格式,直接跳过构造data字典的步骤即可。
  • Pandas本身支持更高效的向量化操作,但按照你的需求,这里使用了for循环+if判断的实现方式。

内容的提问来源于stack exchange,提问作者kang yep sng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:40:27