将panda dataframe中的列表转换为列

2024-05-31 23:59:51 发布

您现在位置:Python中文网/ 问答频道 /正文

city        state   neighborhoods       categories
Dravosburg  PA      [asas,dfd]          ['Nightlife']
Dravosburg  PA      [adad]              ['Auto_Repair','Automotive']

我有上面的数据帧,我想把列表的每个元素转换成列,例如:

^{pr2}$

我使用以下代码来执行此操作:

def list2columns(df):
"""
to convert list in the columns 
of a dataframe
"""
columns=['categories','neighborhoods']
for col in columns:    
    for i in range(len(df)):
        for element in eval(df.loc[i,"categories"]):
            if len(element)!=0:
                if element not in df.columns:
                    df.loc[:,element]=0
                else:
                    df.loc[i,element]=1
  1. 如何以更有效的方式做到这一点?在
  2. 为什么我用的时候还有下面的警告航向位置已经

    SettingWithCopyWarning: A value is trying to be set on a copy of a slice
    from a DataFrame.Try using .loc[row_indexer,col_indexer] = value instead
    

Tags: columnsoftoindfforlenif
2条回答

因为您使用的是eval(),所以我假设每个列都有一个列表的字符串表示,而不是列表本身。另外,与上面的例子不同,我假设您的neighborhoods列(df.iloc[0, 'neighborhoods'] == "['asas','dfd']")中的列表中的项目有引号,因为否则eval()将失败。在

如果这些都是正确的,您可以尝试如下方法:

def list2columns(df):
"""
to convert list in the columns of a dataframe
"""
columns = ['categories','neighborhoods']
new_cols = set()      # list of all new columns added
for col in columns:    
    for i in range(len(df[col])):
        # get the list of columns to set
        set_cols = eval(df.iloc[i, col])
        # set the values of these columns to 1 in the current row
        # (if this causes new columns to be added, other rows will get nans)
        df.iloc[i, set_cols] = 1
        # remember which new columns have been added
        new_cols.update(set_cols)
# convert any un-set values in the new columns to 0
df[list(new_cols)].fillna(value=0, inplace=True)
# if that doesn't work, this may:
# df.update(df[list(new_cols)].fillna(value=0))

我只能猜测你第二个问题的答案,关于SettingWithCopy警告。在

使用df.iloc而不是df.loc可能会有帮助,因为这是按行号选择的(在您的例子中,df.loc[i, col]只会起作用,因为您没有设置索引,所以pandas使用默认索引,它与行号匹配)。在

另一种可能是传入函数的df已经是一个较大数据帧的片段,这将导致SettingWithCopy警告。在

我还发现,将df.loc与混合索引模式(行的逻辑选择器和列名称的列名称)一起使用会产生带有复制警告的设置;很可能切片选择器也会导致类似的问题。在

希望上面代码中更简单、更直接的索引可以解决这些问题。但是如果您仍然看到警告,请报告(并提供生成df)的代码。在

用这个代替

def list2columns(df):
    """
    to convert list in the columns 
    of a dataframe
    """
    df = df.copy()
    columns=['categories','neighborhoods']
    for col in columns:    
        for i in range(len(df)):
            for element in eval(df.loc[i,"categories"]):
                if len(element)!=0:
                    if element not in df.columns:
                        df.loc[:,element]=0
                    else:
                        df.loc[i,element]=1
    return df

相关问题 更多 >