首页 > 解决方案 > 使用数据框的每 2 列创建一个新数据框

问题描述

我是 Python 新手,我正在为此苦苦挣扎。

我想创建许多新的数据框,每个数据框都来自现有数据框中的列。原件的格式为Time, x1, Time2, x2...

我已经找到了一个循环来搜索“时间”

for col in df.columns:
    if 'Time' in col:

我需要调用找到的列和它旁边的列,并将其分配给具有 ['Time', 'x1'] 列的新数据框,然后循环遍历每对 Timen 和 xn。我想用 xn 命名数据框。

谢谢你的帮助。

标签: pythonpandas

解决方案


如果我正确解释了您的问题,我认为您想要的是df.iloc[<row index>, <column index>].

如果您的数据框始终格式化为Time1, x1, Time2, x2, ..., TimeN, xN(因为您总是抓取连续的列来制作新的数据框),您可以使用以下操作:

df_1 = df.iloc[ : , [0,1] ]

:中的将<row_index>选择所有行,而[0,1]中的<column index>是您想要的列索引列表。

然后,您可以遍历原始数据框中的列数以获取每一对:

# number of columns in your dataframe
number_of_columns = len(df.columns)

# store the split dataframes in a list
split_dfs = []

# loop over column indexes with step size 2
for i in range(0, number_of_columns, 2):
    split_dfs.append(df.iloc[:, [i,i+1]])

推荐阅读