Skip to content Skip to sidebar Skip to footer

Typeerror: Cannot Concatenate Object Of Type ''; Only Series And Dataframe Objs Are Valid

my data which called car_A : Source 0 CAULAINCOURT 1 MARCHE DE L'EUROPE 2 AU MAIRE I would like to find from all path from sources to destination something like: S

Solution 1:

Another solution, using DataFrame.merge():

import pandas as pd

df = pd.DataFrame({'Source': [
    "CAULAINCOURT",
    "MARCHE DE L'EUROPE",
    "AU MAIRE"
]})

df = df.assign(key=1).merge(df.assign(key=1), on='key').drop('key', 1).rename(columns={'Source_x':'Source', 'Source_y':'Destination'})
df = df[df.Source != df.Destination]

print(df)

Prints:

               Source         Destination
1        CAULAINCOURT  MARCHE DE L'EUROPE2        CAULAINCOURT            AU MAIRE
3  MARCHE DE L'EUROPE        CAULAINCOURT
5  MARCHE DE L'EUROPE            AU MAIRE
6            AU MAIRE        CAULAINCOURT
7            AU MAIRE  MARCHE DE L'EUROPE

Solution 2:

A small variation on the fine answer from @James. itertools.permutations removes the duplicates for you.

import pandas as pd
from itertools import permutations

df = pd.DataFrame({'sources': [
    "CAULAINCOURT",
    "MARCHE DE L'EUROPE",
    "AU MAIRE"
]})

df_pairs = pd.DataFrame(
    [x forxinpermutations(df.sources, 2)],
    columns=['source', 'dest'])

df_pairs
# returns
               source                dest
0        CAULAINCOURT  MARCHE DE L'EUROPE1        CAULAINCOURT            AU MAIRE
2  MARCHE DE L'EUROPE        CAULAINCOURT
3  MARCHE DE L'EUROPE            AU MAIRE
4            AU MAIRE        CAULAINCOURT
5            AU MAIRE  MARCHE DE L'EUROPE

Solution 3:

You can use itertools.product to build a set of all of the pairs, filter to remove when the source and destination are the same location, and then construct a new data frame.

import pandas as pd
from itertools import product

df = pd.DataFrame({'sources': [
    "CAULAINCOURT",
    "MARCHE DE L'EUROPE",
    "AU MAIRE"
]})

df_pairs = pd.DataFrame(
    filter(lambda x: x[0]!=x[1], product(df.sources, df.sources)), 
    columns=['source', 'dest']
)

df_pairs
# returns:
               source                dest
0        CAULAINCOURT  MARCHE DE L'EUROPE
1        CAULAINCOURT            AU MAIRE
2  MARCHE DE L'EUROPE        CAULAINCOURT
3  MARCHE DE L'EUROPE            AU MAIRE
4            AU MAIRE        CAULAINCOURT
5            AU MAIRE  MARCHE DE L'EUROPE


Post a Comment for "Typeerror: Cannot Concatenate Object Of Type ''; Only Series And Dataframe Objs Are Valid"