python - 如何从数据框列创建随机值列表?
问题描述
目标:从 df1 中的现有列在 df2 中创建一个新的随机值列。df1 来自我正在阅读的“原始”excel 文件,而 df2 是我在 python 中制作的新数据框。我最终想要 df2 列的一个数据单元格中的 df1 列中的三个随机值。下面的例子。
鉴于此源 excel 文件 (NBA.xlsx):
df1:
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 列的内容,其中有三个随机(或 df1 中相应列中三个最常见的数据值)。
df2: | 列名 | 样本值 | | -------- | ------------- | | Final_Game_Day | 2020 年 10 月 11 日;2019 年 6 月 13 日;2018 年 6 月 8 日 | | 冠军 | 勇士;湖人队;猛龙队 | | 最有价值球员 | 勒布朗·詹姆斯; 凯文杜兰特;科怀·伦纳德 | | String_Example |勒布朗第四次夺冠;湖人队以追平第17名的成绩获胜;猛龙队以三连胜的优势赢得了第一个冠军;勇士横扫骑士连续夺冠 | 天天要闻 | Average_Viewership_(百万) | 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 Sample Values List for Sample Values
SampleValues = []
# Loop over list of Excel files
for f in FileList_xlsx:
ReadXlsx = pd.read_excel(f)
ColumnNames = list(ReadXlsx.columns.values)
# Sets up first column list in df2
for a in ColumnNames:
Agg_ColumnNames.append(a)
for a in ColumnNames:
### Missing code here ###
# Create final dataframe - Need Sample Values at end
final = {'Column_Name': Agg_ColumnNames, }
解决方案
要从列中获取n
最常见的值,您可以使用返回的索引value_counts
:
n = 3
>>> df1["MVP"].value_counts().index[:n].to_list()
['Kevin Durant', 'LeBron James', 'Andre Iguodala']
所以,为了得到你的,你可以从字典理解中的每一列中获取三个最常见的值,df2
然后做 string.join
它看起来像这样:
df2 = pd.Series({column: "; ".join(str(s) for s in df1[column].value_counts().index[:3]) for column in df1.columns}).reset_index()
df2.columns = ["Column_Name", "Sample_Values"]
>>> df2
Column_Name Sample_Values
0 Final_Game_Day 10/11/2020; 6/8/2018; 6/12/2017
1 Champion Warriors; Cavaliers; Raptors
2 MVP Kevin Durant; LeBron James; Andre Iguodala
3 String_Example Toronto wins 1st championship denying Warriors...
4 Average_Viewership_(millions) 17.56; 20.38; 7.45
推荐阅读
- javascript - 对象数组的多级排序 - javascript
- sql - Postgresql - 将数值更改为另一种格式
- php - Wordpress - 嵌套 WP_Query 循环重复内容
- html - 尝试从静态 HTML 制作 WP 主题;CSS 未链接到 HTML 并且无法确定原因
- go - 具有相同接收函数实现的两个结构,如何删除重复项
- javascript - 我无法显示柱形图(Google Chart - 服务器端)
- excel - 计算可能更改行的单元格
- c# - 一个大型 DB 请求加上许多 Casts 与许多单个 DB 请求 - 这对于大量数据来说更快
- ruby-on-rails - Rails 在哪里定义了“邮件”方法
- c# - C# spawn manager 太快地创建一波又一波的敌人