我正在学习python,并从Kaggle获取了一个数据集,以进一步了解python中的数据探索和可视化。你知道吗
我有一个数据框中的“烹饪”列,格式如下:
North Indian, Mughlai, Chinese
Chinese, North Indian, Thai
Cafe, Mexican, Italian
South Indian, North Indian
North Indian, Rajasthani
North Indian
North Indian, South Indian, Andhra, Chinese
我想用逗号分隔此列,并从此列中获取唯一值。我希望将这些唯一值作为新列添加回原始数据帧。你知道吗
根据其他帖子,我尝试了以下方法:
1)转换为列表、设置和展开以获得唯一值
Type函数返回列的序列。将其转换为list,然后再转换为set,将抛出一个错误
type(fl1.cuisines)
pandas.core.series.Series
cuisines_type = fl1['cuisines'].tolist()
type(cuisines_type)
list
cuisines_type
#this returns list of cuisines
cuisines_set = set([ a for b in cuisines_type for a in b])
TypeError: 'float' object is not iterable
2)将其转换为数组和列表
cs = pd.unique(fl1['cuisines'].str.split(',',expand=True).stack())
type(cs)
Out[141]: numpy.ndarray
cs.tolist()
此返回列表。但我无法剥离已添加到某些元素中的空间。你知道吗
预期输出是菜系的唯一列表,并将其添加回列:
北印度| Mughlai |华人
输出
使用
pd.assign
将这些列添加回原始df我相信您需要^{} ,如果可能的话,每个列的重复项将删除它们
max
-对于计数值,输出总是0
或1
的sum
:使用^{} 解决方案也有类似的可能性:
将您的fie保存为csv,然后使用pandas
.read_csv()
方法加载它。然后对每列进行解析,将每列放入各自的列表中,然后获取每个列表的唯一值。你知道吗使用这些新列表中的值初始化一个新的数据帧,这些值现在具有唯一的条目。你知道吗
注意:只要确保你所有的列表都是相同的长度,这个工作。你知道吗
希望这有帮助:))
相关问题 更多 >
编程相关推荐