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
为什么我用的时候还有下面的警告航向位置已经
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
因为您使用的是
eval()
,所以我假设每个列都有一个列表的字符串表示,而不是列表本身。另外,与上面的例子不同,我假设您的neighborhoods
列(df.iloc[0, 'neighborhoods'] == "['asas','dfd']"
)中的列表中的项目有引号,因为否则eval()将失败。在如果这些都是正确的,您可以尝试如下方法:
我只能猜测你第二个问题的答案,关于SettingWithCopy警告。在
使用
df.iloc
而不是df.loc
可能会有帮助,因为这是按行号选择的(在您的例子中,df.loc[i, col]
只会起作用,因为您没有设置索引,所以pandas使用默认索引,它与行号匹配)。在另一种可能是传入函数的
df
已经是一个较大数据帧的片段,这将导致SettingWithCopy警告。在我还发现,将
df.loc
与混合索引模式(行的逻辑选择器和列名称的列名称)一起使用会产生带有复制警告的设置;很可能切片选择器也会导致类似的问题。在希望上面代码中更简单、更直接的索引可以解决这些问题。但是如果您仍然看到警告,请报告(并提供生成
df
)的代码。在用这个代替
相关问题 更多 >
编程相关推荐