Сначала мы создадим ваши столбцы ProductID, Commodity, Country
, вычтя информацию из столбца country/commodity
:
str.split
str.extract
Series.where
Series.mask
str.contains
Затем мы GroupBy
на ProductID
, чтобы получить информацию о соответствующих продуктах вместе, и мыиспользуйте для этого named aggregation
, что является новым с pandas 0.25.0
:
# Extract information from country/commodity
df['ProductID'] = df['country/commodity'].str.split(' ', 1).str[0].str.extract('(\d+)').ffill()
df['Commodity'] = df['country/commodity'].str.split('\d+').str[-1].where(df['Unit'].notna())
df['Country'] = df['country/commodity'].mask(df['country/commodity'].str.contains('\d+')).fillna('')
# Groupby ProductID to get information together
df_new = df.groupby(['ProductID']).agg(
Commodity=('Commodity', 'first'),
Country=('Country', ', '.join),
Unit=('Unit', 'first'),
Quantity=('Quantity', 'first'),
Value=('Value', 'first')
).reset_index()
# Remove unnecessary comma's
df_new['Country'] = df_new['Country'].str.lstrip(', ')
Выход
ProductID Commodity Country Unit Quantity \
0 0011101 BREEDING BULLS (OXEN) DUBAI NO NaN
1 0011102 BREEDING BULLS (BUFFALO) SRI LUNKA NO 248.0
2 0011103 BUFFALO,BREEDING SRI LUNKA NO NaN
3 0011104 COWS BREEDING AJMAN, CYPRUS NO 1249.0
Value
0 75.0
1 1921.0
2 90.0
3 258921665.0