import pandas as pd

创建一个长度为5136的空DataFrame

df = pd.DataFrame(index=range(5136))

添加一列名为'date',初始值为None

df['date'] = None

第1到48行的数据为2020年1月1日,赋值为'2020-01-01'

df.loc[0:47, 'date'] = '2020-01-01'

第49到96行的数据也为2020年1月1日,赋值为'2020-01-01'

df.loc[48:95, 'date'] = '2020-01-01'

按照每48行循环,将日期赋值给相应的行

for i in range(2, 108): start = (i - 1) * 48 end = i * 48 - 1 date = '2020-01-{:02d}'.format(i) df.loc[start:end, 'date'] = date

查看结果

print(df.head()) print(df.tail())

要在一个 DataFrame 中添加一列date其中第 1到48 行的数据为 2020 年 1 月 1 日第 49到96 行的数据为 2020 年 1 月 1 日一直到第 5136 行。请用类似代码写出上述问题的答案new_col = i for j in range1 108 for i in j48

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

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