Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 熊猫;将重复的ID值拆分为多列_Python 3.x_Pandas - Fatal编程技术网

Python 3.x 熊猫;将重复的ID值拆分为多列

Python 3.x 熊猫;将重复的ID值拆分为多列,python-3.x,pandas,Python 3.x,Pandas,我希望有一个数据框架,包含唯一的ID和两行中的项。我需要将项目拆分为多个列,以便项目后面有一个ID 例如:- ID Item 101 pen 101 pencil 101 eraser 101 bottle 102 book 102 pen 102 pencil 102 crayons 103 sketch book 103 A4 sheet 103 Book 103 NoteBook 如何将该df转换为以下值:- ID Item1 Item2 Item3 Item4

我希望有一个数据框架,包含唯一的ID和两行中的项。我需要将项目拆分为多个列,以便项目后面有一个ID

例如:-

ID  Item
101 pen
101 pencil
101 eraser
101 bottle
102 book
102 pen
102 pencil
102 crayons
103 sketch book
103 A4 sheet
103 Book
103 NoteBook
如何将该df转换为以下值:-

ID  Item1   Item2     Item3     Item4
101 pen     pencil    eraser    bottle
102 book    pen       pencil    crayons
103 sketch  A4 sheet  Book      NoteBook

以下内容应起作用,使用

两者都将产生以下结果 输出:


代码中的注释定义方法

  • 为ID创建项目列表
  • 使用
    pd.Series
  • 根据需要重命名列,并使ID再次成为列
输出
欢迎使用,请注意,这不是代码编写或辅导服务。我们可以帮助解决特定的技术问题,而不是无限期的代码或建议请求。请编辑您的问题,以显示到目前为止您尝试了什么,以及您需要帮助解决的具体问题。有关如何最好地帮助我们帮助您的详细信息,请参见页面。#使用set创建唯一元组。id=[101101102103103]项目=[‘笔’、‘铅笔’、‘橡皮擦’、‘瓶子’、‘书’、‘笔’、‘铅笔’、‘蜡笔’、‘素描本’、‘A4纸’、‘书’]组合=[(id[索引],项目)用于索引,枚举(项目)中的项目]组合=set(组合)df=pd.DataFrame(组合,列=[‘代码’,‘项目’])打印(*df groupby('code'))['item'])
res = pd.DataFrame(df.groupby('ID').apply(lambda g: g['Item'].values))
res[['Item1','Item2','Item3','Item4']] = pd.DataFrame(res[0].tolist(), index= res.index)
res.drop(0,axis=1,inplace=True)
res
res = df.groupby('ID')
pd.DataFrame(res.apply(lambda g: g['Item'].values).to_list(),index=[key for key, _ in res]).reset_index().rename({'index':'ID',0:'Item1',1:'Item2',2:'Item3',3:'Item4'},axis=1)
ID  Item1   Item2     Item3     Item4
101 pen     pencil    eraser    bottle
102 book    pen       pencil    crayons
103 sketch  A4 sheet  Book      NoteBook
import io
df = pd.read_csv(io.StringIO("""ID  Item
101  pen
101  pencil
101  eraser
101  bottle
102  book
102  pen
102  pencil
102  crayons
103  sketch book
103  A4 sheet
103  Book
103  NoteBook"""), sep="\s\s+", engine="python")

df = (
      # list of all items for an ID
 df.groupby("ID").agg({"Item":lambda s: list(s)})
    # expand list to columns
 ["Item"].apply(pd.Series)
    # name columns as per requirement
 .rename(columns={n:f"Item{n+1}" for n in range(10)})
    # make ID a column again
 .reset_index()
)
    ID        Item1     Item2   Item3     Item4
0  101          pen    pencil  eraser    bottle
1  102         book       pen  pencil   crayons
2  103  sketch book  A4 sheet    Book  NoteBook