我想创建一个包含 feature1
、month
和 feature_segment
列的 DataFrame。我在 feature1
和 3 个 feature_segments
中有超过 3,000 个唯一值,我现在必须将每个功能映射到每个月和 feature_segment
,
例如: feature1 = 1 因此映射应创建一个数据框,如下所示:
feature1 month feature_Segment
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
1 4 1
1 4 2
1 4 3
1 5 1
1 5 2
1 5 3
1 6 1
1 6 2
1 6 3
1 7 1
1 7 2
1 7 3
1 8 1
1 8 2
1 8 3
1 9 1
1 9 2
1 9 3
1 10 1
1 10 2
1 10 3
1 11 1
1 11 2
1 11 3
1 12 1
1 12 2
1 12 3
现在有什么方法可以在不使用 for 循环的情况下创建此数据框吗?
所有 df 列都在列表中。
最佳答案
from itertools import product
feature = [1]
feature_Segment = [1,2,3]
month = range(1, 13)
df = pd.DataFrame(product(feature, month, feature_Segment),
columns=['feature1','month','feature_Segment'])
print (df.head(10))
feature1 month feature_Segment
0 1 1 1
1 1 1 2
2 1 1 3
3 1 2 1
4 1 2 2
5 1 2 3
6 1 3 1
7 1 3 2
8 1 3 3
9 1 4 1
关于python - 除了 for 循环之外更好的方法,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61555034/