用给定属性在数据框中添加列

发布于 2025-02-13 15:59:15 字数 452 浏览 1 评论 0原文

我有以下数据框架,

df = pd.DataFrame({'a': [[5.4, 15.3],[2.0,9.1]],'b':[[9.8,2.0],[9.7,6.0,1.2]]})

我想使用分配函数添加列“ C”,以便“ C”中的每个元素是将“ A”中相应列表的元素加倍后获得的元素列表。 我写了以下代码”,

df.assign(c=np.array(df['a'])*2)

但它给出了错误的输出。 我期望输出如下所示:

        a                 b            c             
0  [5.4, 15.3]       [9.8, 2.0]   [10.8, 30.6]
1   [2.0, 9.1]  [9.7, 6.0, 1.2]   [4.0, 18.2]

I have the following dataframe,

df = pd.DataFrame({'a': [[5.4, 15.3],[2.0,9.1]],'b':[[9.8,2.0],[9.7,6.0,1.2]]})

I want to add a column 'c' using assign function such that each element in 'c' is a list of elements we get after doubling up the elements of corresponding list in 'a'.
I wrote the below code'

df.assign(c=np.array(df['a'])*2)

But it gave the wrong output.
I'm expecting the output as shown below:

        a                 b            c             
0  [5.4, 15.3]       [9.8, 2.0]   [10.8, 30.6]
1   [2.0, 9.1]  [9.7, 6.0, 1.2]   [4.0, 18.2]

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

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

发布评论

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

评论(2

墨小墨 2025-02-20 15:59:15

您几乎可以使用列表理解来创建一个新列表,并分配给DF ['c'],如下所示;

df['c'] = [np.array(x)*2 for x in df['a'].to_list()]

You are almost there you can utilize list comprehension to create a new list and assign to df['c'] as follows;

df['c'] = [np.array(x)*2 for x in df['a'].to_list()]
拒绝两难 2025-02-20 15:59:15

添加新列真的很容易

df = pd.DataFrame({'a':[1,2,3],'b':[1,1,1]})
df['c'] = [5,5,5]
print(df)

It is really easy to add new column

df = pd.DataFrame({'a':[1,2,3],'b':[1,1,1]})
df['c'] = [5,5,5]
print(df)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文