我想在现有数据框中添加一个新列。新列需要从第一行的常量值开始(在下面的示例中为-17.3),然后连续为所有26000行添加0.15。新列最后应具有以下值:
-17.3-17.15-17-16.85………26000 rows
-17.3
-17.15
-17
-16.85
…
26000 rows
有没有什么方法可以在不循环遍历所有行的情况下完成这一操作?谢谢你,芳郎
tag5nh1u1#
您可以按如下方式构建范围:
# 26,000 numbers# step of 0.15# starting at -17.3np.arange(26000) * 0.15 - 17.3
# 26,000 numbers
# step of 0.15
# starting at -17.3
np.arange(26000) * 0.15 - 17.3
jobtbby32#
假设您的 Dataframe 名为df,您可以通过以下方式进行命名:
df
start_value = -17.3increment_value = 0.15new_column = [start_value + increment_value * i for i in range(df.shape[0])]df['new_column'] = new_column
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
mm9b1k5b3#
将pandas.Series * 构造函数 * 与pandas.Series.cumsum一起使用:
pandas.Series
pandas.Series.cumsum
N, S, F = len(df), -17.3, 0.15 # <- len(df) = 26000 in your casedf["approach_1"] = pd.Series([S] + [np.NaN]*(N-1)).fillna(F).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()
或者按照@tdy 简单地选择numpy.arange:
numpy.arange
df["approach_2"] = np.arange(S, S + N*F, F)
输出:
print(df) approach_1 approach_20 -17.30 -17.301 -17.15 -17.152 -17.00 -17.003 -16.85 -16.854 -16.70 -16.70... ... ...25995 3881.95 3881.9525996 3882.10 3882.1025997 3882.25 3882.2525998 3882.40 3882.4025999 3882.55 3882.55[26000 rows x 2 columns]
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]
3条答案
按热度按时间tag5nh1u1#
您可以按如下方式构建范围:
jobtbby32#
假设您的 Dataframe 名为
df
,您可以通过以下方式进行命名:mm9b1k5b3#
将
pandas.Series
* 构造函数 * 与pandas.Series.cumsum
一起使用:或者按照@tdy 简单地选择
numpy.arange
:输出: