python - 在 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}
解决方案
推荐阅读
- r - dnorm() 如何在 sapply 循环中处理分位数向量
- c# - 复制到另一个文本文件时如何覆盖或跳过特定行
- r - 如何将一系列日期更改为一个日期 R?
- python - 我正在尝试使用 def 对性别 = 男性和性别 = 女性的数据框进行有条件的添加
- bing-maps - 有没有办法对 bingmap 的信息框关闭按钮进行编程?
- mysql - 如何使用内部连接查询和 where like 子句从表 Produto_precos 中获取另外两个值
- javascript - 检查当前页面上是否存在数组中的任何类并使用 jQuery 将匹配的类保存为变量
- r - 每个“组”从起点到终点的动画
- javascript - 记录 PostCSS 运行的插件是什么?
- powershell - 俄罗斯符号。powershell - zabbix_sender