I have an original dataframe og_df and a sublist dataframe, which is a part of the og_df. I want to create a new dataframe new_df which contains the elements of og_df and every n following elements in the og_df.
Example:

og_df = pd.DataFrame({'column': range(20)})
sub_df = pd.DataFrame({'column': [ 1, 2, 10 ]})
n = 3  
new_df = pd.DataFrame({'column':[]})

for index in sub_df.index:
    new_df = pd.concat([new_frame, og_df.iloc[index:index + n]])
print(new_df)

>>>    column
    0    1
    1    2
    2    3
    1    2
    2    3
    3    4
    11   10
    12   11
    13   12

这是我想要的方式,并给出了预期的结果.然而,当og_df有多列,我使用[..]操作符,或者如果它有一列,我使用[..]操作符,它的行为是这样的:

for index in sub_df.index:
    new_df = pd.concat([new_frame, og_df['column'].iloc[index:index + n]])
print(new_df)

>>>    column     0
1      NaN   1.0
2      NaN   2.0
3      NaN   3.0
2      NaN   2.0
3      NaN   3.0
4      NaN   4.0
10     NaN  10.0
11     NaN  11.0
12     NaN  12.0

我怎样才能让它像你想要的那样运行呢?我的目标是从多列og_df中 Select 一列,这就是我使用[..]操作符的原因.

推荐答案

你面临的问题是你使用的是单切片[]而不是双切片[[]].

如果你更新你的循环,代码可以工作:

new_df = pd.DataFrame({'column':[]})
for index in sub_df.index:
    new_df = pd.concat([new_df, og_df[['column']].iloc[index:index + n]])
print(new_df)

输出:

   column
0     0.0
1     1.0
2     2.0
1     1.0
2     2.0
3     3.0
2     2.0
3     3.0
4     4.0

这是因为单个切片给出了一个序列:

type(og_df['column']), type(og_df[['column']])
(pandas.core.series.Series, pandas.core.frame.DataFrame)

Python相关问答推荐

仅从风格中获取 colored颜色 循环

Pythind 11无法弄清楚如何访问tuple元素

线性模型PanelOLS和statmodels OLS之间的区别

Pytest两个具有无限循环和await命令的Deliverc函数

优化pytorch函数以消除for循环

Mistral模型为不同的输入文本生成相同的嵌入

使用@ guardlasses. guardlass和注释的Python继承

如何在python polars中停止otherate(),当使用when()表达式时?

如何在solve()之后获得症状上的等式的值

如何获得每个组的时间戳差异?

DataFrames与NaN的条件乘法

如何在BeautifulSoup/CSS Select 器中处理regex?

找到相对于列表索引的当前最大值列表""

30个非DATETIME天内的累计金额

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

read_csv分隔符正在创建无关的空列

与同步和异步客户端兼容的Python函数

为什么在不先将包作为模块导入的情况下相对导入不起作用

我可以同时更改多个图像吗?

如何在基于时间的数据帧中添加计算值