Python - 将 Pandas 类型转换为 set


要将熊猫类型转换为 Set,请使用 set()。首先,我们创建一个 DataFrame -

dataFrame = pd.DataFrame(
   {
      "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],
      "Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North']
   }
)

将 pandas 类型转换为 set,然后执行 set union -

set(dataFrame.EmpName) | set(dataFrame.Zone)

示例

以下是完整的代码 -

import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],
      "Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North']
   }
)

print"DataFrame ...\n",dataFrame

# Pandas into Set
print"\nTypecast Pandas into Set...\n",set(dataFrame.EmpName) | set(dataFrame.Zone)

输出

将生成以下输出 -

DataFrame ...
    EmpName   Zone
0      John   North
1       Ted   South
2     Jacob   South
3  Scarlett   East
4       Ami   West
5       Ted   East
6  Scarlett   North

Typecast Pandas into Set...
set(['Ami', 'East', 'North', 'West', 'Ted', 'South', 'Jacob', 'John', 'Scarlett'])

更新于:15-Sep-2021

122 次浏览

开启您的 职业生涯

完成此课程进行认证

立即开始
广告