【问题标题】:Python Pandas find element in a listPython Pandas 在列表中查找元素
【发布时间】:2016-12-09 22:51:19
【问题描述】:

我从 pandas 数据框创建了两个列表,如下所示:-

List1:由文件夹中的多个 csv 文件创建,如下所示...

import glob as gb
csv_files = gb.glob("csv\\*.csv")

# csv_files = csv_files[0:]

# Create list of the CSV in dataframes
dfList = []
for file in csv_files:
    df_csv = pd.read_csv(file, header=None)
    dfList.append(df_csv)    

# print (dfList)

# Convert each dataframe within the list into individual list
new_dfList = []
for ind_df in dfList:
    # Convert the dataframe to a list
    new_convert = ind_df.values.tolist()
    new_dfList.append(new_convert)

List2:由包含关键字的文本文件创建,如下所示。

# Open keywords TEXT file
keywords = pd.read_csv("words.txt", header=None)

# Convert the dataframe to a list
keywords = keywords.values.tolist()

# Move out from inner list
# keywords = list(chain(*keywords))

# print (keywords)
keywords[0]

list2 中的这些关键字将与 list1 中的每个列表进行比较。我该怎么做?

如何使第一个关键字(在 list2 中)转到第一个列表(在 list1 中),第二个关键字(在 list2 中)转到第二个列表(在 list1 中),第三个关键字(在 list2 中)转到第三个列表(在 list1 中)。 ...等等搜索并返回匹配结果?

【问题讨论】:

    标签: python list pandas


    【解决方案1】:

    你为什么不在 pandas 中做呢?

    keywords = pd.read_csv("words.txt", header=None)
    
    dfList = []
    for file in csv_files:
        df_csv = pd.read_csv(file, header=None)
        dfList.append(df_csv)
    
    df = pd.concat(dfList, keys=keywords)
    # Or, make a panel
    wp = pd.Panel(dict(zip(keywords, dfList)))
    # Or, just leave it as a dictionary
    df_dict = dict(zip(keywords, dfList))
    

    如果你真的想要一个列表字典:

    df_dict_list = dict(zip(keywords, [df.tolist() for df in dfList]))
    

    【讨论】:

      猜你喜欢
      • 2010-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 2012-04-11
      • 2018-12-11
      • 1970-01-01
      • 2022-12-28
      相关资源
      最近更新 更多