Yao*_*ung 2 python dataframe pandas
我想根据列表生成一个范围列表,以从数据帧中对行进行子集。
import numpy as np
import pandas as pd
start_index = [10,20,30]
end_index = [15,25,35]
range_list = [10:15, 20:25, 30:35]
# assume df is a dataframe with 50 rows
df = df.loc[np.r_range_list,:]
Run Code Online (Sandbox Code Playgroud)
如何从 start_index 和 end_index 生成 range_list?欢迎任何建议!
使用zip与list元组的列表:
range_list = list(zip(start_index, end_index))
print (range_list)
[(10, 15), (20, 25), (30, 35)]
Run Code Online (Sandbox Code Playgroud)
然后使用列表理解进行过滤:
dfs = [df.loc[s:e] for s, e in range_list]
Run Code Online (Sandbox Code Playgroud)
如果想要一个大的 DataFrame 添加concat:
dfbig = pd.concat(dfs)
Run Code Online (Sandbox Code Playgroud)
一起,将zip对象转换为列表是没有必要的:
dfbig = pd.concat([df.loc[s:e] for s, e in zip(start_index, end_index)])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
95 次 |
| 最近记录: |