python - 类型错误 : cannot concatenate object of type '<class ' str'>'; only Series and DataFrame objs are valid

标签 python pandas dataframe

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

关于python - 类型错误 : cannot concatenate object of type '<class ' str'>'; only Series and DataFrame objs are valid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544302/

相关文章:

python - 为字典中的一个键附加多个值

python - 使用 pandas 读取和更新 XLSM 文件中的工作表,同时保留 VBA 代码

python - 合并 2 个 csv 文件 - html 编码

具有多个条件和计算的 Pandas 数据框

python - 如何根据列值乘以 2 个不相等的数据框?

python - 如何在特定条件下从 Pandas 数据框中选择行

Python 正则表达式 : get all group's sequence

python - 如何在 Python 中使用 pyodbc 将光标更改到下一行

python - 使用 JSON 序列化/反序列化 Pandas DataFrame 时如何保持索引的时区

python - 为什么不同 Pandas DataFrame 之间相同值的这些哈希值不同?