如何使用循环按规则选取行创建满足长度要求的新DataFrame
完整实现代码
import pandas as pd # 构造原始DataFrame,修正了原数据中Lisa字段的引号语法错误 raw_data = { 'Mon': [1,7,0,4,2,8], 'Tue': [8,4,2,5,9,3], 'Wed': [0,5,1,1,4,3], 'Thu': [8,6,5,7,6,8], 'Fri': [4,5,4,6,5,7] } index_names = ['Lucy','Guzy','Lisa','Kala','Lura','kim'] df = pd.DataFrame(raw_data, index=index_names) n = 3 target_length = 6 result_df = pd.DataFrame(columns=df.columns) current_start_idx = 0 # 外层循环控制起始行偏移,直到结果长度达标 while len(result_df) < target_length: current_row_idx = current_start_idx # 内层循环按间隔n取行 while current_row_idx < len(df): if len(result_df) >= target_length: break # 取出当前行加入结果 result_df = pd.concat([result_df, df.iloc[[current_row_idx]]]) current_row_idx += n current_start_idx += 1 print(result_df)
运行结果
Mon Tue Wed Thu Fri Lucy 1 8 0 8 4 Kala 4 5 1 7 6 Guzy 7 4 5 6 5 Lura 2 9 4 6 5 Lisa 0 2 1 5 4 kim 8 3 3 8 7
逻辑说明
- 完全采用循环实现,未使用切片、内置取数函数等快捷操作
- 从第0行开始,每次间隔3行取行加入结果集,超过原始表行范围后,起始行向后移1位,重复间隔取数操作,直到结果集长度达到要求的6行
- 可通过修改
n和target_length变量适配其他间隔和目标长度需求
内容的提问来源于stack exchange,提问作者newbzzs
相关产品推荐
相关产品推荐

