将熊猫数据框中的列表转换为列

时间:2016-05-27 02:43:47

标签: python list pandas dataframe data-analysis

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

我有以上数据框我想将列表的每个元素转换为列,例如:

city        state asas dfd adad Nightlife Auto_Repair Automotive 
Dravosburg  PA    1     1   0   1         1           0    

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

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. 为什么我在使用df.loc时仍然出现以下警告

    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
    

2 个答案:

答案 0 :(得分:2)

改为使用

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

答案 1 :(得分: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混合索引模式(列的行和列名称的逻辑选择器)会产生SettingWithCopy警告;您的切片选择器可能会导致类似的问题。

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