I am trying to kreate a nested loop to calculate the price combinations between the Car ModelName, e.g.:
fact_date CarID Country Type ManufactureNameSum Sum_Costs 2017-07-14 1 USA Car Ford_Focus____VW_Jetta 34003
which means I have a combination of the ManufactorName and ModelName and the sum of the AcquisitionPrice. Somehow I receive the results twice due to the nested loop but just want to have it once. I was thinking solving it with the following line:
row['ManufactureName'] != row2['ManufactureName']
but this only solves the problem with the same ManufactureName but not the one having due to two lists twice the result.
Hope somehone could help here.
Adjustment
I adjusted the code for the nested loop, but still have the propblem concerning the fact_date indexing as I had before.
Adjusted Code:
import pandas as pd
df = pd.read_csv('C:/Sales_Cars.csv', encoding='cp1252', sep=';', index_col=0).dropna()
df2 = pd.DataFrame([])
for current_date in df.index.unique():
for i in range(0, len(df)):
for j in range(i+1, len(df)):
if (
df.iloc[i]['ManufactureName'] != df.iloc[j]['ManufactureName'] and
df.iloc[i]['CarID'] == df.iloc[j]['CarID'] and
df.iloc[i]['Country'] == df.iloc[j]['Country']):
df2 = df2.append(
pd.DataFrame({
'CarID': df.iloc[i]['CarID'],
'Country': df.iloc[i]['Country'],
'Type': df.iloc[i]['Type'],
'ManufactureNameSum': (
df.iloc[i]['ManufactureName'] +
'_' +
df.iloc[i]['ModelName'] +
'____' +
df.iloc[j]['ManufactureName'] +
'_'+df.iloc[j]['ModelName']
),
'Sum_Costs': (
df.iloc[i]['AcquisitionPrice'] +
df.iloc[j]['AcquisitionPrice']
)
}, index=[0]), ignore_index=True)
print(df2)
The data looks like the following:
fact_date CarID ManufactureName ModelName Type Country AcquisitionPrice 2017-07-14 1 Ford Focus Car USA 11640 2017-07-14 2 Ford Mustang Car USA 12994 2017-07-14 3 Ford Fiesta Car USA 12842 2017-07-14 4 Ford Mondeo Car USA 14685 2017-07-14 1 VW Jetta Car USA 22363 2017-07-14 2 VW Polo Car USA 20107 2017-07-14 3 VW Golf Car USA 21256 2017-07-14 4 VW Parteon Car USA 23679 2017-07-14 1 Toyota Prius Car USA 14384 2017-07-14 2 Toyota Avensis Car USA 14821 2017-07-14 3 Toyota Corolla Car USA 12480 2017-07-14 4 Toyota Land Cruiser Car USA 11502 2017-07-14 1 BMW 1er Car USA 35127 2017-07-14 2 BMW 2er Car USA 43924 2017-07-14 3 BMW 3er Car USA 40573 2017-07-14 4 BMW 4er Car USA 36690 2017-07-14 1 Mercedes C-Klasse Car USA 36646 2017-07-14 2 Mercedes A-Klasse Car USA 40912 2017-07-14 3 Mercedes B-Klasse Car USA 39060 2017-07-14 4 Mercedes E-Klasse Car USA 41838
itertools.combinationsand use one loop, personally