gpt4 book ai didi

python - 将上一行的内容追加到下一行

转载 作者:行者123 更新时间:2023-12-02 02:56:38 26 4
gpt4 key购买 nike

这里有点卡住了。看起来很简单,但由于某种原因似乎无法让它发挥作用。

我有一个 csv 文件,需要读取该文件,然后将前一行的内容添加到下一行。例如,如果原始数据如下所示:

   0
0 a
1 b
2 c
3 d

然后我需要让它像这样:

   a  b  c
0 a 0 0
1 b a 0
2 c b a
3 d c b

我首先尝试使用 Pandas,但很快就迷失在试图找到一种简单而快速的迭代行/列的方法中。

毕竟这并不完全有效,我决定简单地逐行读取 csv,然后递归地将数据添加到前一行的内容中,但到目前为止一直不成功,不断遇到递归限制问题等。

解决这个问题的最佳方法是什么?

最佳答案

只需一个 for 循环即可:

for i in range(1,3):
# may need to replace '0' with 0 or the actual column name
# also i with f'{i}' if you want column name as string
df[i] = df['0'].shift(i, fill_value=0)

# another column to shift:
df[f'other_col_{i}'] = df['other_col'].shift(i, fill_value=0)

如果您有两列以上,也许类似于 ALollz 的优秀已删除答案:

cols = ['col1', 'col2', 'col3']
new_df = pd.concat([df[cols].shift(i, fill_value=0).add_suffix(f'_{i}')
for i in range(3)
])

输出:

   0  1  2
0 a 0 0
1 b a 0
2 c b a
3 d c b

关于python - 将上一行的内容追加到下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60982927/

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