繁体   English   中英

类型错误:无法连接类型为 &#39; 的对象<class 'str'> &#39;; 只有 Series 和 DataFrame 对象有效

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

我的数据称为 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

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

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

来自@James 的好答案的一个小变化。 itertools.permutations为您删除重复项。

import pandas as pd
from itertools import permutations

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

df_pairs = pd.DataFrame(
    [x for x in permutations(df.sources, 2)],
    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

您可以使用itertools.product构建所有对的集合,当源和目标位于相同位置时过滤以移除,然后构建新的数据框。

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


暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM