【问题标题】:How to convert the dataframe to a desired format?如何将数据框转换为所需的格式?
【发布时间】:2021-04-25 12:34:38
【问题描述】:

我希望将数据帧转换为特定格式。

示例数据框如下:

Col1
a
b
c

我想通过分成两列将上述数据框转换为以下格式:

Col1  Col2
a      a
a      b
a      c
b      b
b      c
c      c

我正在尝试获取Col1 列的所有组合。

【问题讨论】:

  • 这是什么逻辑?
  • @sammywemmy 他想要这些组合

标签: python pandas dataframe data-manipulation


【解决方案1】:

你可以试试itertools.combinations_with_replacement:

from itertools import combinations_with_replacement as comb
df = pd.DataFrame(list(comb(df['Col1'], 2)), columns=['Col1', 'Col2'])
print(df)

输出:

  Col1 Col2
0    a    a
1    a    b
2    a    c
3    b    b
4    b    c
5    c    c
>>> 

编辑:

感谢@QuangHoang 的评论,他提到对于更高版本(Quang Hoang 有 1.1.4),您可以这样做:

df = pd.DataFrame(comb(df['Col1'], 2), columns=['Col1', 'Col2'])

没有list(...)。而对于较低版本,您可以获得:

TypeError: data argument can't be an iterator

【讨论】:

  • 我认为只要pd.DataFrame(comb(df['Col1'], 2), columns=['Col1','Col2']) 就可以了。
  • @QuangHoang 哦,是的!这是正确的!编辑了我的,也赞成你的回答:)很好
  • @QuangHoang 唯一的问题是我仍然必须保留list(...),否则它会给出:TypeError: data argument can't be an iterator
  • 我的 Pandas 1.1.4 接受迭代器。所以comb 无需环绕list 即可工作。
【解决方案2】:

看起来像交叉合并:

df['key'] = 1

df.merge(df,on='key').query('Col1_x<=Col1_y').drop(['key'],axis=1)

输出:

  Col1_x Col1_y
0      a      a
1      a      b
2      a      c
4      b      b
5      b      c
8      c      c

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2019-11-21
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多