python - 连接 pandas Dataframe 中的行

标签 python pandas dataframe

这看起来应该简单得多,但我在这里。

我试图从另一个数据帧向一个数据帧(确切地说是 2 个数据帧)添加一行,但出现以下错误:

TypeError: cannot concatenate object of type "<class 'numpy.float64'>"; only pd.Series, pd.DataFrame, and pd.Panel (deprecated) objs are valid

我的代码

for i in range(0,len(k_means_labels_unique)):
    X = pd.DataFrame(columns=['first occurrence of \'AB\'','similarity to \'AB\''])
    y = pd.DataFrame(columns=['Class'])
    for row in result.iterrows():
        data=row[1]
        if data['cluster ID'] == i:
            X = pd.concat([X,data['first occurrence of \'AB\''],data['similarity to \'AB\'']])
            y = pd.concat([y,data['Class']])

我必须转型data['first occurrence of \'AB\''],data['similarity to \'AB\'']到另一个数据框?这看起来效率极低

编辑:我尝试过 y = pd.concat([y,pd.Series(data['Class'])])但这将数据附加为新列,例如 y :

columns

最佳答案

您需要首先转换为数据帧:

X = pd.concat([X,pd.DataFrame([[data['first occurrence of \'AB\''],data['similarity to \'AB\'']]],columns=['first occurrence of \'AB\'','similarity to \'AB\''])], ignore_index=True)
y = pd.concat([y,pd.DataFrame([data['Class']], columns=['Class'])], ignore_index=True)

编辑:添加ignore_index=True

关于python - 连接 pandas Dataframe 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50643118/

相关文章:

python - Django 按外键 bool 字段排序

python - PySpark 2.4.5 : IllegalArgumentException when using PandasUDF

r - 如何过滤掉特定列全部为na的位置

r - 将 "dist"类的对象转换为 r 中的数据帧

python - 设置基于值计数和分组依据的数据框列值

python - 如果选择全部并按下删除或退格按钮,则条目 Tkinter 不允许删除数据

python - 使用 xlrd 和 xlwt 编辑现有的 excel 工作簿和工作表

python - 如何在Python中读取一般用户格式的矩阵

Python Pandas : Is Order Preserved When Using groupby() and agg()?

python - 选择一列中的特定值并从 pandas 的另一列中获取之前/之后的 n 行