gpt4 book ai didi

python - 用每行增加的列偏移量填充 pandas 数据框

转载 作者:行者123 更新时间:2023-12-01 01:48:33 30 4
gpt4 key购买 nike

我正在尝试创建一个 pandas 数据框,其中每行都填充相同的值集,但对于向下迭代数据框的每一行,每行的起始列都会增加 1。这是我当前的方法,以及我希望获得的数据框的示例。我在这里做错了什么?

谢谢!

import pandas as pd
import numpy as np

df_to_fill = pd.DataFrame(data=np.zeros((4,6)),columns=[1,2,3,4,5,6])

values_to_fill = pd.Series(np.arange(1,4))

# vars to iterate over dataframe
num_rows = len(df_to_fill)
# counter to keep track of how many columns to offset from to fill dataframe in loop below
col_offset = 0

for row in range(0,num_rows):
# Fill the first row from first column onwards, 2nd from 2nd column onwards,...
df_to_fill.iloc[row,col_offset:] = values_to_fill
# Fill the remaining columns in the row with the last value from the values to fill series
df_to_fill.iloc[row,:].fillna(values_to_fill.values[-1],inplace=True)
col_offset += 1

offset_array = np.array([[1,2,3,3,3,3],[0,1,2,3,3,3],[0,0,1,2,3,3]])
desired_df = pd.DataFrame(data=offset_array,columns=[1,2,3,4,5,6])

最佳答案

您可以使用 shift + concat 创建与第一行相同的填充值

values_to_fill = pd.Series(np.arange(1,4),index=np.arange(1,4)).reindex(np.arange(1,7)).ffill().astype(int)

pd.concat([values_to_fill.shift(x) for x in range(num_rows)],axis = 1 ).T.fillna(0)
1 2 3 4 5 6
0 1.0 2.0 3.0 3.0 3.0 3.0
1 0.0 1.0 2.0 3.0 3.0 3.0
2 0.0 0.0 1.0 2.0 3.0 3.0
3 0.0 0.0 0.0 1.0 2.0 3.0

关于python - 用每行增加的列偏移量填充 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978353/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com