[英]Create new dense column in Pandas Dataframe by joining together two sparse columns
我有一個包含三列的數據框,“組織名稱”,“類型”,“組織類型”。 “類型”和“組織類型”是同一回事。 我想創建一個名為“組織類型”的新列,該列在“類型”列中使用字符串,如果“類型”列為空,則在“組織類型”列中使用名稱。
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'列和'Org的類型'列合並在一起,以創建一個完整的列,因為這兩個列都缺少一些數據,但是它們所擁有的數據將是相同的。 如果有更好的方法可以解決這些問題,我很樂意提供任何建議-只是不確定解決此問題的最佳方法是什么? 一會兒循環?
此功能稱為combine_first
:
df.Type.combine_first(df['Type of Org'])
Out[332]:
0 Retail
1 Service
2 Comm
3 Tech
4 Retail
Name: Type, dtype: object
一種方法是在對那些丟失的行進行子設置之前,將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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.