首页 > 解决方案 > 在 Python/Pandas 数据框中创建列,显示 Excel 源中相应列中的数据示例

问题描述

目标:创建一个列: 1. 显示三个最常见的条目,或 2:显示源 Excel 文件中列的三个随机离散条目。我知道那是很多话,让我演示一下。在下面的示例中,我无法编写代码来生成下面第二个表(示例值列)最右侧列中的内容。

鉴于此源 excel 文件 (NBA.xlsx):

Final_Game_Day 冠军 MVP String_Example Average_Viewership_(百万)
2020 年 10 月 11 日 湖人队 勒布朗·詹姆斯 勒布朗第四次夺冠;湖人队追平第17名 7.45
2019 年 6 月 13 日 猛龙队 科怀·伦纳德 多伦多队赢得第一个冠军否认勇士队三连冠 15.14
2018 年 6 月 8 日 勇士 凯文杜兰特 勇士队连续横扫骑士队夺冠 17.56
2017 年 6 月 12 日 勇士 凯文杜兰特 杜兰特离开雷霆后先夺冠 20.38
2016 年 6 月 19 日 骑士队 勒布朗·詹姆斯 骑士队赢得他们的第一个冠军 20.28
2015 年 6 月 16 日 勇士 安德烈·伊戈达拉 伊戈达拉第6人夺得MVP 19.94

我想:

---------- 列名 文件名 数据类型 Sample_Values
File1.Final_Game_Day Final_Game_Day NBA.xlsx 日期时间64[ns] 2020 年 10 月 11 日;2019 年 6 月 13 日;2018 年 6 月 8 日
文件1.冠军 冠军 NBA.xlsx 目的 勇士;湖人队;猛龙队
文件1.MVP MVP NBA.xlsx 目的 勒布朗·詹姆斯; 凯文杜兰特;科怀·伦纳德
File1.String_Example String_Example NBA.xlsx 目的 勒布朗第四次夺冠;湖人队以追平第17名的成绩获胜;猛龙队以三连胜的优势赢得了第一个冠军;勇士队连续横扫骑士队夺冠
File1.Average_Viewership_(百万) Average_Viewership_(百万) NBA.xlsx 浮动64 7.45; 15.14;17.56

我将在下面提供代码。这很长,但我想告诉你我正在使用什么。我想我只需要在最后两部分中添加一些代码片段,用 # 符号表示:

### Setting up
import pandas as pd
import os
import glob

###Setting working directory
path = os.getcws()
files = os.listdir(path)

### Prep to get all files
from os import listdir
from os.path import isfile, join

### Reading only excel files in folder
FileList_xlsx = [f for f in files if f[-4:] == "xlsx"]

# Initializing empty data frame
df = pd.DataFrame()

# Initializing Aggregate List for Column Names
Agg_ColumnNames = []

# Initializing Aggregate List for File Names associated with Column Names
FileNames = []

# Initializing empty dataframe for Data Type
datatype_df = pd.DataFrame()

# Read excel into Python and prepping the dataframe for DATA TYPE ONLY
n = 1
for f in FileList_xlsx:
    test_df = pd.read_excel(f)
    test_df = test_df.add_prefix(f'File{n}.')
    datatype_df = datatype_df.append(test_df, ignore_index=True, sort = False)
    n+=1

# Getting the data type of the column

dataTypeSeries = datatype_df.dtypes

# Loop over list of Excel files

for f in FileList_xlsx:
    ReadXlsx = pd.read_excel(f)
    ColumnNames = list(ReadXlsx.columns.values)

    for a in ColumnNames:
        Agg_ColumnNames.append(a)
    
    for a in ColumnNames:
        FileNames.append(f)

# Create final dataframe
final = {'Column_Name': Agg_ColumnNames, 'File_Name': FileNames, 'Data_Type': dataTypeSeries}

标签: pythonexcelpandasdataframe

解决方案


推荐阅读