使用 pandas iloc 进行赋值,其中 RHS 长度短于 LHS

发布于 2025-01-16 22:31:22 字数 257 浏览 4 评论 0原文

我正在尝试对从第 20 行开始的数据帧执行 np.where 函数。我输入的代码如下:

df['buy'] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')

它显示以下错误: ValueError:值的长度(226)与索引的长度(246)不匹配

有人知道如何修复它吗?

我希望 pandas 从第 20 行开始返回值。

I am trying to perform np.where function on a dataframe starting from row 20 onward. The code that I entered as follow:

df['buy'] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')

It showed the error below:
ValueError: Length of values (226) does not match length of index (246)

Anyone know how to fix it please?

I want pandas to return value from row 20 onward.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦里泪两行 2025-01-23 22:31:22

这是一个赋值错误,df 有 246 个条目,但您试图为其分配一个具有 226 个值的 numpy 向量。

你想要的结果应该是什么?

你可以对数据框进行子集化吗?

df_sub = df.iloc[20:].copy()
df_sub['buy']=np.where((df_sub.iloc['signal']==1), 'buy','no buy')

This is an assignment error, df has 246 entries, but you are trying to assign a numpy vector with 226 values to it.

What do you intend the result should be?

you could subset the dataframe?

df_sub = df.iloc[20:].copy()
df_sub['buy']=np.where((df_sub.iloc['signal']==1), 'buy','no buy')

若水般的淡然安静女子 2025-01-23 22:31:22

IIUC,您可以对作业使用“混合”索引:

n = df.columns.get_loc('buy')
df.iloc[20:, n] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')

IIUC, you could use "mixed" indexing for the assignment:

n = df.columns.get_loc('buy')
df.iloc[20:, n] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文