[英]TypeError: cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid I got this error
giving a unique code by seeing the first column string and the second columns string and whenever the first column string change it starts from 1通过查看第一列字符串和第二列字符串并在第一列字符串更改时从 1 开始给出唯一代码
i use this code我用这个代码
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)
Your code can be updated in the following way:您的代码可以通过以下方式更新:
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
Returns退货
It is not very clear what you expect, but when you write df[1] for df in dfs
, then your df
is a key (for example Kebele 1 ) and df[1]
is a character (for example e - second character of the string).您的期望不是很清楚,但是当您df[1] for df in dfs
,您的df
是一个键(例如Kebele 1 )并且df[1]
是一个字符(例如e - 第二个字符字符串)。
That is why you get this error, because your array dfs
is constructed out of 2 characters ["e", "e"]
.这就是您收到此错误的原因,因为您的数组dfs
是由 2 个字符["e", "e"]
构成的。 Therefore you can not concatenate it.因此你不能连接它。
I think with df[1]
you meant the data frame, that is associated with the key, if so, then the code should look like this:我认为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.