[英]Merging column values in a data frame in Pandas / Python
我正在嘗試合並同一數據框中的列(B和C列)的值。 B和C有時具有相同的值。 B中的某些值存在於C中,而C中的某些值存在於B中。最終結果將顯示一列,該列是兩列的組合。
A B C D
Apple Canada '' RED
Bananas '' Germany BLUE
Carrot US US GREEN
Dorito '' '' INDIGO
A B C
Apple Canada RED
Bananas Germany BLUE
Carrot US GREEN
Dorito '' INDIGO
IIUC
df['B']=df[['B','C']].replace("''",np.nan).bfill(1).loc[:,'B']
df=df.drop('C',1).rename(columns={'D':'C'})
df
Out[102]:
A B C
0 Apple Canada RED
1 Bananas Germany BLUE
2 Carrot US GREEN
3 Dorito NaN INDIGO
您可以對字符串進行排序並采用最后一個字符串:
df['B'] = df[['B', 'C']].apply(lambda x: x.sort_values()[1], axis=1)
df=df.drop('C', 1).rename(columns={'D':'C'})
print(df)
輸出:
A B C
0 Apple Canada RED
1 Bananas Germany BLUE
2 Carrot US GREEN
3 Dorito '' INDIGO
另一種方法是巧妙地使用列表理解:
# Make sets of the column B and C combined to get rid of duplicates
k = [set(b.strip() for b in a) for a in zip(df['B'], df['C'])]
# Flatten sets to strings
k = [''.join(x) for x in k]
# Create desired column
df['B'] = k
df.drop('C', axis=1, inplace=True)
print(df)
A B D
0 Apple Canada RED
1 Bananas Germany BLUE
2 Carrot US GREEN
3 Dorito INDIGO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.