列表列名称ITERTOOLS
我有此数据框:
STATE CITY TAX_C MATERIAL IG LIMIT
0 TX DALLAS 1 CARP 0 5
1 TX DALLAS 1 BLAY 0 10
我已经使用itertools创建了一个循环,该iTertools将每一行的每一列的组合组合在一起:
res = []
for r in range(2,len(df.columns)+1):
for cols in itertools.combinations(df.columns, r ):
res += df[list(cols)].T.to_dict('list').values()
res
它给了我这个输出:
[[TX, DALLAS], [TX, DALLAS], [DALLAS, 1], [DALLAS 1], [1, CARP], [1, BLAY], [CARP, 0], [0,5], [TX, 1],...]
我正在尝试获取一个输出,该输出在每个值之前都打印出列名称。 :
[[STATE: 'TX', CITY: 'DALLAS'], [STATE: 'TX', CITY: 'DALLAS'], [CITY: 'DALLAS', TAX_C: '1'], [CITY: 'DALLAS', TAX_C: '1'], [TAX_C: '1', MATERIAL: 'CARP']...]
I have this Dataframe:
STATE CITY TAX_C MATERIAL IG LIMIT
0 TX DALLAS 1 CARP 0 5
1 TX DALLAS 1 BLAY 0 10
And I've created a loop using itertools that takes the combinations of every column from each row:
res = []
for r in range(2,len(df.columns)+1):
for cols in itertools.combinations(df.columns, r ):
res += df[list(cols)].T.to_dict('list').values()
res
And it gives me this output:
[[TX, DALLAS], [TX, DALLAS], [DALLAS, 1], [DALLAS 1], [1, CARP], [1, BLAY], [CARP, 0], [0,5], [TX, 1],...]
I am trying to get an output that prints out the Column name before each value like so:
[[STATE: 'TX', CITY: 'DALLAS'], [STATE: 'TX', CITY: 'DALLAS'], [CITY: 'DALLAS', TAX_C: '1'], [CITY: 'DALLAS', TAX_C: '1'], [TAX_C: '1', MATERIAL: 'CARP']...]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,我像这样重现了您的数据
,我认为第一步是更深入地了解如何从数据框架中获取字典,
如果
我们更深入地,您可以循环浏览它,并附加列表,这样
收益
的 请注意,您在Python中无法描述。某物是列表或词典。列表仅与逗号相隔。
我希望这会有所帮助:)
So I reproduced your data like so
And I think the first step is to go a little deeper into how you can get dictionary out of the dataframe
Which yields
If we go a little deeper you can loop over it and append a list like so
yielding
Please note that you description is not possible in Python. Something is a list or a dictionary. A list is separated with comma's only.
I hope this helps :)
尝试以下代码:
区别在于我将参数从 to_dict 中删除,因此它可以与 dict 的默认方向一起工作。
结果的最初部分是:
因此,它是词典的列表,与您所需的结果非常相似。
Try the following code:
The difference is that I dropped the argument from to_dict, so it works with the default orientation of dict.
The initial part of the result is:
so it is a list of dictionaries, quite similar to your desired result.
我认为您正在寻找
pairwise
而不是组合
来自itertools
-output
I think you are looking for
pairwise
and notcombinations
fromitertools
-Output