简体   繁体   English

Pandas dataframe 列移位加

[英]Pandas dataframe column shift and add

I would like to add a new column to existing dataframe. The new column needs to start with a constant value in the first row (-17.3 in the example below) and then consecutively add 0.15 to it for all 26000 rows.我想向现有的 dataframe 添加一个新列。新列需要在第一行中以常量值开始(在下面的示例中为 -17.3),然后为所有 26000 行连续添加 0.15。 The new column should have following values in the end:新列最后应具有以下值:

-17.3
-17.15
-17
-16.85
…
…
…
26000 rows

Is there any way to get this done without looping over all the rows?有没有办法在不遍历所有行的情况下完成这项工作?

Thanks,谢谢,

Yoshiro义郎

You can construct the range like this:您可以像这样构建范围:

# 26,000 numbers
# step of 0.15
# starting at -17.3
np.arange(26000) * 0.15 - 17.3

Let's say your dataframe is named df , you can do it in the following way:假设您的 dataframe 名为df ,您可以通过以下方式进行操作:

start_value = -17.3
increment_value = 0.15
new_column = [start_value + increment_value * i for i in range(df.shape[0])]
df['new_column'] = new_column

Either usepandas.Series constructor with pandas.Series.cumsum :pandas.Series构造函数pandas.Series.cumsum一起使用:

N, S, F = len(df), -17.3, 0.15 # <- len(df) = 26000 in your case

df["approach_1"] = pd.Series([S] + [np.NaN]*(N-1)).fillna(F).cumsum()

Or simply go for numpy.arange as per @ tdy :或者只是 go 为numpy.arange按照@tdy

df["approach_2"] = np.arange(S, S + N*F, F)

Output: Output:

print(df)

       approach_1  approach_2
0          -17.30      -17.30
1          -17.15      -17.15
2          -17.00      -17.00
3          -16.85      -16.85
4          -16.70      -16.70
...           ...         ...
25995     3881.95     3881.95
25996     3882.10     3882.10
25997     3882.25     3882.25
25998     3882.40     3882.40
25999     3882.55     3882.55

[26000 rows x 2 columns]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM