簡體   English   中英

TypeError: 無法連接 ' 類型的 object<class 'str'> '; 只有 Series 和 DataFrame objs 是有效的我得到了這個錯誤</class>

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

通過查看第一列字符串和第二列字符串並在第一列字符串更改時從 1 開始給出唯一代碼

例子在此處輸入圖像描述

我用這個代碼

dfs = dict(tuple(df.groupby('colummen1')))
for _, df in dfs.items():

 df['id'] = df.groupby(['colummen1','colummun2']).ngroup()  

dfs = [df[1] for df in dfs]
df = pd.concat(dfs)

但我得到了流動錯誤在此處輸入圖像描述

您的代碼可以通過以下方式更新:

import pandas as pd

# set data
data = {"colummen1": ["Kenbele1", "Kenbele1", "Kenbele1", "Kenbele1", "Kenbele2", "Kenbele2", "Kenbele2", "Kenbele2"], 
        "colummun2": ["Commutity1", "Commutity2", "Commutity3", "Commutity4", "Commutity1", "Commutity2", "Commutity3", "Commutity4"]}

# create dataframe
df = pd.DataFrame(data)

dfs = df.groupby('colummen1')

dfs_updated = []

for _, df in dfs:
    df['id'] = df.groupby(['colummen1','colummun2']).ngroup()+1
    dfs_updated.append(df)
    
df_new = pd.concat(dfs_updated)

df_new

退貨

在此處輸入圖像描述

您的期望不是很清楚,但是當您df[1] for df in dfs ,您的df是一個鍵(例如Kebele 1 )並且df[1]是一個字符(例如e - 第二個字符字符串)。

這就是您收到此錯誤的原因,因為您的數組dfs是由 2 個字符["e", "e"]構成的。 因此你不能連接它。

我認為df[1]你的意思是數據框,它與鍵相關聯,如果是這樣,那么代碼應該如下所示:

dfs = dict(tuple(df.groupby('colummen1')))

for _, df in dfs.items():
    df['id'] = df.groupby(['colummen1','colummun2']).ngroup()  

dfs = [df for _, df in dfs.items()]
df = pd.concat(dfs)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM