Combine Two Lists in python in dataframe with file name added in one column and content in another

a 夏天 提交于 2021-01-29 13:59:33

问题


I have a list of files in a folder in my system

file_list= ["A", "B", "C"]

I Have read the files using a for loop and have obtained content which is as follows

A = ["A1", "B1", "C1"]
B = ["E1", "F1"]
C = []

I would like the following output

    Content  Name
      A1     A
      B1     A
      C1     A
      D1     B
      E1     B
             C

How do I accomplish this.


回答1:


Try this

import pandas as pd

data = list(zip((A, B, C), file_list))

df = pd.DataFrame(data, columns=['Content', 'Name'])
df = df.explode('Content')
print(df)

Output:

  Content Name
0      A1    A
0      B1    A
0      C1    A
1      E1    B
1      F1    B
2     NaN    C


来源:https://stackoverflow.com/questions/63571922/combine-two-lists-in-python-in-dataframe-with-file-name-added-in-one-column-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!