'; 只有 Series 和 DataFrame obj 是有效的,python,pandas,dataframe"/>

首页 > 解决方案 > TypeError: 无法连接类型为 ' 的对象'; 只有 Series 和 DataFrame obj 是有效的

问题描述

我的数据称为 car_A :

    Source
0   CAULAINCOURT
1   MARCHE DE L'EUROPE
2   AU MAIRE

我想从从源到目的地的所有路径中找到类似的东西:


    Source                    Destination
0 CAULAINCOURT           MARCHE  DE L'EUROPE
2 CAULAINCOURT                AU MAIRE
3 MARCHE DE L'EUROPE        AU MAIRE
.
.
.

我已经尝试过

for i in car_A['Names']:
  for j in range(len(car_A)-1):
    car_A = car_A.append(car_A.iloc[j+1,0])

但我得到了

TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

我怎样才能得到提到的数据集?

标签: pythonpandasdataframe

解决方案


另一种解决方案,使用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)

印刷:

               Source         Destination
1        CAULAINCOURT  MARCHE DE L'EUROPE
2        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

推荐阅读