简体   繁体   English

如何在不重复其他列值的情况下扩展 pandas dataframe 中的列表

[英]How to expand a list in a pandas dataframe without repeating other column values

I was wondering how I would be able to expand out a list in a cell without repeating variables in other cells.我想知道如何在不在其他单元格中重复变量的情况下扩展单元格中的列表。

之前的数据框

之后的数据框

The goal is to get it so that the list is expanded but the first column is not repeated.目标是获取它以便扩展列表但不会重复第一列。 I know how to expand the list out but I would not like to have the first column values repeated if that is possible.我知道如何扩展列表,但如果可能的话,我不想重复第一列的值。 Thank you for any help!!感谢您的任何帮助!!

In order to get what you're asking for, you still have to use explode() to get what you need.为了得到你想要的东西,你仍然必须使用explode()来得到你需要的东西。 You just have to take it a step further and change the values of the first column.您只需要更进一步并更改第一列的值。 Please note that this will destroy the association between the elements of the list and the letter of the row they were first in. You would be creating a third value for the column (an empty string) that would be repeated for every record not beginning with 1.请注意,这将破坏列表元素与它们所在行的字母之间的关联。您将为该列创建第三个值(一个空字符串),该值将为每条不以开头的记录重复1.

If you want to eliminate the value from the rows you are talking about but still want to have those records associated with the value that their list was associated with, you can't.如果您想从您正在谈论的行中删除值,但仍希望这些记录与其列表相关联的值相关联,则不能。 It's not logically possible for a value to both be in a given cell but also not be in that cell.一个值既在给定单元格中又不在该单元格中在逻辑上是不可能的。 So, I will show you the steps for eliminating the original association.因此,我将向您展示消除原始关联的步骤。

For this example, I named the columns since they are not provided.对于此示例,我命名了列,因为它们没有提供。

data = [
    ["a",["1 hey","2 hi","3 hello"]],
    ["b",["1 what","2 how","3 say"]]
]
df = pd.DataFrame(data,columns=["first","second"])
df = df.explode("second")
df['first'] = df.apply(lambda x: x['first'] if x['second'][0] == '1' else '', axis=1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM