从数据框架创建一个名为Tuples的列表

发布于 2025-02-03 13:12:48 字数 493 浏览 2 评论 0原文

我有一个类似的数据帧:

DF1

Name   Category  Age
Harry   A        11
James   B        23
Will    A        19

我想使用new nationtuplecollections创建一个元组列表。列表应该是这样的:

output_list = [Variable(Name='Harry', Age=11), Variable(Name='James', Age=23), Variable(Name='Will', Age=19)]

这是我尝试使用的“ iTertuples”

output_list = list(df1[["Name","Age"]].itertuples(name='Variable', index=False))

I have a dataframe like this:

df1

Name   Category  Age
Harry   A        11
James   B        23
Will    A        19

I want to create a list of tuples using namedtuple from collections. The list should be like this:

output_list = [Variable(Name='Harry', Age=11), Variable(Name='James', Age=23), Variable(Name='Will', Age=19)]

This is what I've tried using 'itertuples'

output_list = list(df1[["Name","Age"]].itertuples(name='Variable', index=False))

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

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

发布评论

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

评论(2

林空鹿饮溪 2025-02-10 13:12:48

尝试:

from collections import namedtuple

COLS = ['Name', 'Age']
Variable = namedtuple('Variable', field_names=COLS)
output_list = df[COLS].apply(lambda x: Variable(**x), axis=1).tolist()
print(output_list)

# Output
[Variable(Name='Harry', Age=11),
 Variable(Name='James', Age=23),
 Variable(Name='Will', Age=19)]

Try:

from collections import namedtuple

COLS = ['Name', 'Age']
Variable = namedtuple('Variable', field_names=COLS)
output_list = df[COLS].apply(lambda x: Variable(**x), axis=1).tolist()
print(output_list)

# Output
[Variable(Name='Harry', Age=11),
 Variable(Name='James', Age=23),
 Variable(Name='Will', Age=19)]
北恋 2025-02-10 13:12:48

也许不是您要寻找的答案:

tuples = [tuple(x) for x in df1[['Name','Age']].to_numpy()]
tuples

输出:

[('Harry', 11), ('James', 23), ('Will', 19)]

Maybe not the answer you're looking for but:

tuples = [tuple(x) for x in df1[['Name','Age']].to_numpy()]
tuples

Output:

[('Harry', 11), ('James', 23), ('Will', 19)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文