通过将两个稀疏列连接在一起,在数据帧中创建新的密集列

2024-04-26 09:24:55 发布

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

我有一个有三列的数据框,'组织名称','类型','组织类型'“类型”和“组织类型”是一回事。我想创建一个名为“Org Type”的新列,它接受“Type”列中的字符串,如果“Type”列为空,则接受“Type of Org”列中的名称。你知道吗

Example of current dataframe:
Name of Organization     Type      Type of Org     
Tyco                     Retail    Retail          
Mac                      Service
Lis                                Comm
Ice                      Tech
Rex                      Retail    Retail


Example of New dataframe: 
Name of Organization     Type      Type of Org    Org Type
Tyco                     Retail    Retail         Retail
Mac                      Service                  Service
Lis                                Comm           Comm
Ice                      Tech                     Tech
Rex                      Retail    Retail         Retail

基本上,我尝试将“Type”列和“Type of Org”列连接在一起,以便创建一个完整的列,因为这两个列都缺少一些数据,但它们所拥有的数据将是相同的。如果有更好的方法来做这些,我会喜欢任何建议-只是不知道什么是最好的方式来处理这个问题?一段时间?你知道吗


Tags: of数据nameorg名称类型dataframeexample
2条回答

一种方法是在对缺少的行进行子集设置之前,将Org Type列设置为Type列。如果Type列包含缺少的值(不仅仅是空字符串),那么下面的操作应该可以完成。如果它确实包含空字符串或类似的字符串,那么您可以在Type列等于这些值的地方创建子集。你知道吗

df['Org Type'] = df['Type']
df.loc[df['Org Type'].isnull(), 'Org Type'] = \
    df.loc[df['Org Type'].isnull(), 'Type of Org']

此功能称为^{}

df.Type.combine_first(df['Type of Org'])
Out[332]: 
0     Retail
1    Service
2       Comm
3       Tech
4     Retail
Name: Type, dtype: object

相关问题 更多 >