根据列表的项目复制 pandas 的行
问题说明
我有一个看起来像这样的熊猫数据框:
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.
谢谢!
正确答案
您可以编写一个简单的清除函数,使其成为列表(假设它不是逗号列表,并且不能简单地使用
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
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20