• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

根据列表的项目复制 pandas 的行

用户头像
it1352
帮助1

问题说明

我有一个看起来像这样的熊猫数据框:

I have a pandas dataframe that looks like this:

COL     data
line1   [A,B,C]

,其中data列中的项目可以是列表,也可以只是逗号分隔的元素.是否有简单的获取方式:

where the items in the data column could either be a list or just comma separated elements. Is there an easy of way of getting:

COL     data
line1   A
line1   B
line1   C

我可以遍历列表并通过python手动复制行,但是这样做有一些 magic 熊猫技巧吗?关键是如何自动复制行.

I could iterate over the list and manually duplicate the rows via python, but is there some magic pandas trick for doing this? The key point is how to automatically duplicate the rows.

谢谢!

正确答案

#1

您可以编写一个简单的清除函数,使其成为列表(假设它不是逗号列表,并且不能简单地使用

You could write a simple cleaning function to make it a list (assuming it's not a list of commas, and you can't simply use ast.literal_eval):

def clean_string_to_list(s):
    return [c for c in s if c not in '[,]']  # you might need to catch errors

df['data'] = df['data'].apply(clean_string_to_list)

遍历行似乎是一个合理的选择:

Iterating through the rows seems like a reasonable choice:

In [11]: pd.DataFrame([(row['COL'], d)
                       for d in row['data']
                       for _, row in df.iterrows()],
                       columns=df.columns)
Out[11]:
     COL data
0  line1    A
1  line1    B
2  line1    C

恐怕我认为熊猫并不专门针对这种操纵.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgjjek
系列文章
更多 icon
同类精品
更多 icon
继续加载