[英]How can I create a pandas data frame from each unique combination of multiple lists?
I'm trying to create a pandas data frame based on every unique combination of four lists of different lengths.我正在尝试基于四个不同长度的列表的每个独特组合创建一个熊猫数据框。 I'm a relative beginner.
我是一个相对初学者。
I constructed a nested list of combinations like so:我构建了一个嵌套的组合列表,如下所示:
combinations = [
[
[
[
[w,x,y,z]for w in sexes
]
for x in ages
]
for y in destination_codes
]
for z in origin_codes
]
Where each of these is a simple list.其中每一个都是一个简单的列表。 This works fine, but I don't know how to get this into a four column frame with one row for each unique combination, like this:
这工作正常,但我不知道如何将其放入一个四列框架中,每个唯一组合都有一行,如下所示:
https://imgur.com/a/b9gNWJa https://imgur.com/a/b9gNWJa
I tried this:我试过这个:
total = pd.DataFrame(columns=['origin', 'destination', 'age', 'sex'])
for first in combinations:
for second in first:
for third in second:
for fourth in third:
summary_table = pd.DataFrame({'Origin': [first], 'Destination': [second], 'Age': [third], 'Sex:' [fourth])
total.append(summary_table)
Which doesn't work at all.这根本不起作用。
Any pointers would be very helpful - I'm not sure if this is a simple error or whether I'm approaching the whole problem in the wrong way.任何指针都会非常有帮助 - 我不确定这是否是一个简单的错误,或者我是否以错误的方式处理整个问题。 Any thoughts?
有什么想法吗?
Is this correct of what you want?这是你想要的吗?
combinations = [
[w,x,y,z]
for w in sexes
for x in ages
for y in destination_codes
for z in origin_codes
]
total_df = pd.DataFrame(combinations, columns=['sex', 'age', 'origin', 'destination'])
But using a list comprehension here can be quite inefficient.但是在这里使用列表理解可能效率很低。 There is a better way to do this using
itertools.product
使用
itertools.product
有更好的方法来做到这一点
from itertools import product
combinations = list(product(ages, ages, origin_codes, destination_codes))
Use itertools.product
.使用
itertools.product
。 It returns the Cartesian product of sequences given as parameters.它返回作为参数给出的序列的笛卡尔积。
Try this one:试试这个:
import pandas as pd
import numpy as np
sexes=["m", "f"]
ages=["young", "middle", "old"]
destination_codes=["123", "039", "0230", "0249"]
origin_codes=["304", "0430", "034i39", "430", "0349"]
combined_ = np.array([[a,b,c,d] for a in sexes for b in ages for c in destination_codes for d in origin_codes])
df=pd.DataFrame(data={"sexes": combined_[:,0], "ages": combined_[:,1], "destination": combined_[:,2], "origin": combined_[:,3]})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.