gpt4 book ai didi

Python 数据框。根据行索引向左移动行值

转载 作者:行者123 更新时间:2023-12-02 02:09:57 24 4
gpt4 key购买 nike

我有这样的表格:

import pandas as pd
data = [[20, 15, 10, 5], [20, 15, 10, 5], [20, 15, 10, 5], [20, 15, 10, 5]]
df = pd.DataFrame(data, columns = ['one', 'two', 'three', 'four'])
df
<表类=“s-表”><标题>一个两个三第四 <正文>2015105201510520151052015105

我想根据行索引向左移动每行值。索引为 0 的行值保持不变,索引为 1 的行值向左移动一点,索引为 2 的行值向左移动两点,等等...所需的表格应如下所示:

<表类=“s-表”><标题>一个两个三第四 <正文>2015105151050105005000

谢谢你帮助我!

最佳答案

另一种方法是使用简单的循环 shift每行中的值,然后使用 fillnaNA 值替换为 0:

for i in range(len(df)):
df.iloc[i,:] = df.iloc[i,:].shift(-i)

df.fillna(0, inplace=True)

输出:

>>> df
one two three four
0 20 15.0 10.0 5.0
1 15 10.0 5.0 0.0
2 10 5.0 0.0 0.0
3 5 0.0 0.0 0.0

关于Python 数据框。根据行索引向左移动行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67859331/

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