从列表列表创建pandas数据帧,但有不同的分隔符

2024-09-21 03:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份清单:

     [['1', 'Toy Story (1995)', "Animation|Children's|Comedy"],
     ['2', 'Jumanji (1995)', "Adventure|Children's|Fantasy"],
     ['3', 'Grumpier Old Men (1995)', 'Comedy|Romance']]

我想用这些列来结束pandas数据帧。在

^{pr2}$

对于'Adventure', 'Children', 'Comedy', 'Fantasy', 'Romance'列,数据将为1或0。在

我试过:

for row in movies_list:
    for element in row:
        if '|' in element:
            element = element.split('|')

但是原始列表没有任何变化。。完全被困在这里。在


Tags: 数据inforelementfantasyrowchildrentoy
2条回答

DataFrame构造函数与^{}一起使用:

L = [['1', 'Toy Story (1995)', "Animation|Children's|Comedy"],
     ['2', 'Jumanji (1995)', "Adventure|Children's|Fantasy"],
     ['3', 'Grumpier Old Men (1995)', 'Comedy|Romance']]
df = pd.DataFrame(L, columns=['MovieID','Name','Data'])


df1 = df['Data'].str.get_dummies()
print (df1)
   Adventure  Animation  Children's  Comedy  Fantasy  Romance
0          0          1           1       1        0        0
1          1          0           1       0        1        0
2          0          0           0       1        0        1

对于列NameYear需要^{}和{a3}来删除尾随),并且{}被转换为ints

^{pr2}$

最后一次删除列Data,并将df1添加到原始列^{}

df = df.drop('Data', axis=1).join(df1)
print (df)
  MovieID              Name  Year  Adventure  Animation  Children's  Comedy  \
0       1         Toy Story  1995          0          1           1       1   
1       2           Jumanji  1995          1          0           1       0   
2       3  Grumpier Old Men  1995          0          0           0       1   

   Fantasy  Romance  
0        0        0  
1        1        0  
2        0        1  

这是我的版本,不足以回答一句话,但希望它能帮助你!在

import pandas as pd
import numpy as np

data = [['1', 'Toy Story (1995)', "Animation|Children's|Comedy"],
     ['2', 'Jumanji (1995)', "Adventure|Children's|Fantasy"],
     ['3', 'Grumpier Old Men (1995)', 'Comedy|Romance']]
cols = ['MovieID', 'Name', 'Year', 'Adventure', 'Children', 'Comedy', 'Fantasy', 'Romance']
final = []
for x in data:
    output = []
    output.append(x[0])
    output.append(x[1].split("(")[0].lstrip().rstrip())
    output.append(x[1].split("(")[1][:4])
    for h in ['Adventure', 'Children', 'Comedy', 'Fantasy', 'Romance']:
        output.append(h in x[2])
    final.append(output)

df = pd.DataFrame(final, columns=cols)
print(df)

输出:

^{pr2}$

相关问题 更多 >

    热门问题