【发布时间】:2017-02-16 20:59:05
【问题描述】:
我正在尝试创建一个整数序列,该序列重复列表中的元素多次,同时在每次重复后为它们添加一个常量偏移量。
我有一个 pandas 数据框,其中有许多列是关于同一 N 个人的重复信息块。例如,列可以是 [age1, age2, age3, ... ageN, height1, height2, height3, ... heightN, ... ],我想要与个人 1 和 4 相关联的列(例如)。我想为特定个人生成列索引,以便可以使用df.iloc[:, cindices] 对数据框进行子集化。
以下代码有效,但它非常难看,我希望有一个更清晰、更清晰的解决方案(更 Pythonic)。
subjects = [1, 4]
N = 11; repeats = 3
columns = np.array([(np.arange(repeats) * N + i) for i in subjects])
cindices = columns.T.flatten()
# Information for individuals 1 & 4 are in these columns:
>> array([ 1, 4, 12, 15, 23, 26])
【问题讨论】:
标签: python pandas numpy sequence repeat