从数据框创建命名元组列表
Create a list of namedtuples from a dataframe
我有一个这样的数据框:
df1
Name Category Age
Harry A 11
James B 23
Will A 19
我想使用 collections
中的 namedtuple
创建一个元组列表。列表应该是这样的:
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))
尝试:
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)]
也许不是您要找的答案但是:
tuples = [tuple(x) for x in df1[['Name','Age']].to_numpy()]
tuples
输出:
[('Harry', 11), ('James', 23), ('Will', 19)]
我有一个这样的数据框:
df1
Name Category Age
Harry A 11
James B 23
Will A 19
我想使用 collections
中的 namedtuple
创建一个元组列表。列表应该是这样的:
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))
尝试:
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)]
也许不是您要找的答案但是:
tuples = [tuple(x) for x in df1[['Name','Age']].to_numpy()]
tuples
输出:
[('Harry', 11), ('James', 23), ('Will', 19)]