Python数据缺失怎么顺延与数据分段求值?


import pandas as pd
import glob
import os

os.chdir('path/stock_hfqqa')  

summ=pd.DataFrame()

for file in glob.glob('*.csv'):
    fname='.'.join(file.split('.')[0:2])

    df=pd.read_csv(file,dtype={'trade_date':'str'})
    df['trade_date']=pd.to_datetime(df['trade_date'])
    df['year']=df['trade_date'].dt.year

    min_row=df[df['year']==2020]['close'].idxmin()
    end_date_min=df.iloc[min_row]['trade_date']
    start_date_min=end_date_min-pd.Timedelta(days=100)
    mindf=df.loc[(df['trade_date']>=start_date_min) & (df['trade_date']<=end_date_min)]
    tempdf=mindf.head(1).copy()
    tempdf['date_start']=start_date_min
    summ=summ.append(tempdf,ignore_index=True)
    filemin=fname+'_min'+'.xlsx'
    mindf.to_excel(filemin,index=False)

    max_row=df[df['year']==2020]['close'].idxmax()
    end_date_max=df.iloc[max_row]['trade_date']
    start_date_max=end_date_max-pd.Timedelta(days=100)
    maxdf=df.loc[(df['trade_date']>=start_date_max) & (df['trade_date']<=end_date_max)]
    tempdf=maxdf.head(1).copy()
    tempdf['date_start']=start_date_max
    summ=summ.append(tempdf,ignore_index=True)   
    filemax=fname+'_max'+'.xlsx'
    maxdf.to_excel(filemax,index=False)

summ=summ[['ts_code','date_start','trade_date','close']]
summ.columns=['ts_code','date_start','date_end','close']
summ.to_excel('bbbb.xlsx',index=False)

计算出的 start_date_min 日期当日可能有数据也可能没数据,当没数据就想顺延到有数据的日期,请问怎么改代码,谢谢。。。。
还有个问题就是2020怎么换成年份字符窜,有知道的一起指教,就是怎么求每只 code 每年的最低最高价,一年一年算很麻烦,就想一下算所有的,一并谢了。。。

阅读 2.2k
1 个回答

CSV 文件:

import pandas as pd
import datetime

# 创建示例数据
data = {
    'trade_date': [datetime.date(2020, i, 1).strftime('%Y-%m-%d') for i in range(1, 13)],
    'ts_code': ['000001.SZ'] * 12,
    'close': [10, 9, 8, 7, 6, 7, 8, 9, 10, 11, 12, 13]
}
df = pd.DataFrame(data)

# 保存为 CSV 文件
df.to_csv('000001.SZ.csv', index=False)

修改:

import os
import glob

# 设置工作目录
os.chdir('/path/to/csv/files')

# 创建 summ DataFrame
summ = pd.DataFrame()

# 遍历 CSV 文件
for file in glob.glob('*.csv'):
    fname = '.'.join(file.split('.')[0:2])
    df = pd.read_csv(file, dtype={'trade_date': 'str'})
    df['trade_date'] = pd.to_datetime(df['trade_date'])
    df['year'] = df['trade_date'].dt.year.astype(str)  # 将年份转为字符串

    # 以下为找到最小值的部分,并使用 bfill() 处理缺失数据
    min_row = df[df['year'] == '2020']['close'].idxmin()
    end_date_min = df.iloc[min_row]['trade_date']
    start_date_min = end_date_min - pd.Timedelta(days=100)
    start_idx_min = df.loc[df['trade_date'] >= start_date_min].index.min()
    if pd.isnull(df.loc[start_idx_min, 'close']):
        start_date_min = df.loc[start_idx_min:].bfill().iloc[0]['trade_date']
    mindf = df.loc[(df['trade_date'] >= start_date_min) & (df['trade_date'] <= end_date_min)]
    tempdf = mindf.head(1).copy()
    tempdf['date_start'] = start_date_min
    summ = summ.append(tempdf, ignore_index=True)
    filemin = fname + '_min' + '.xlsx'
    mindf.to_excel(filemin, index=False)

    # 同理处理最大值的部分
    max_row = df[df['year'] == '2020']['close'].idxmax()
    end_date_max = df.iloc[max_row]['trade_date']
    start_date_max = end_date_max - pd.Timedelta(days=100)
    start_idx_max = df.loc[df['trade_date'] >= start_date_max].index.min()
    if pd.isnull(df.loc[start_idx_max, 'close']):
        start_date_max = df.loc[start_idx_max:].bfill().iloc[0]['trade_date']
    maxdf = df.loc[(df['trade_date'] >= start_date_max) & (df['trade_date'] <= end_date_max)]
    tempdf = maxdf.head(1).copy()
    tempdf['date_start'] = start_date_max
    summ = summ.append(tempdf, ignore_index=True)
    filemax = fname + '_max' + '.xlsx'
    maxdf.to_excel(filemax, index=False)

# 结果保存为 Excel 文件
summ = summ[['ts_code', 'date_start', 'trade_date', 'close']]
summ.columns = ['ts_code', 'date_start', 'date_end', 'close']
summ.to_excel('bbbb.xlsx', index=False)