简体   繁体   English

Pandas:如何从 dataframe 的特定列中获取每个类别的样本行并保存在单个 csv 中?

[英]Pandas: How to get the sample rows from each category from specific column in dataframe and save in single csv?

Below is the dataframe (df).下面是 dataframe (df)。 I want to save the sample of 3 rows from each category of 'country' column.我想从“国家”列的每个类别中保存 3 行的样本。 Following is my code but it's not saving based on category.以下是我的代码,但它不是基于类别保存的。 I need single csv having the samples.我需要单个 csv 有样品。 Please suggest.请建议。

data = {'country':['India', 'Nepal', 'Canada', 'USA','India', 'Nepal', 'Canada', 'USA','India', 'Nepal', 'Canada', 'USA','India', 'Nepal', 'Canada', 'USA','India', 'Nepal', 'Canada', 'USA'],
    'Age':[20, 21, 19, 18,20, 21, 19, 18,20, 21, 19, 18,20, 21, 19, 18,20, 21, 19, 18]}
df = pd.DataFrame(data)

df.sample(n=3).to_csv(sampledata.csv, na_rep='NA', index = False)

GroupBy and then sample GroupBy 然后采样

df.groupby('country').sample(3)

   country  Age
2   Canada   19
6   Canada   19
10  Canada   19
4    India   20
0    India   20
12   India   20
1    Nepal   21
13   Nepal   21
9    Nepal   21
3      USA   18
11     USA   18
19     USA   18

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从数据帧的每个类别中迭代和采样? - How to iterate and sample from each category of a dataframe? 如何从每个子组的 Pandas DataFrame 中统一采样 n 行 - How to sample from pandas DataFrame n rows from each subgroup uniformly Pandas:从 dataframe 中删除以字母开头的行并保存 CSV - Pandas: Remove rows from the dataframe that begin with a letter and save CSV 如何通过为每列选择特定范围来消除 dataframe 中的行? - Pandas - How to eliminate rows in a dataframe by selecting a specific range for each column? - Pandas 将 Pandas Dataframe 中的行与如何处理每一列的特定规则合并 - Merge rows in Pandas Dataframe with specific rules on how to handle each column 从熊猫数据框中随机删除每列中的单个值? - Remove a single value from each column randomly from pandas dataframe? 如何从 csv/tsv 加载 Pandas DataFrame 作为分解类别类型? - How to load a Pandas DataFrame from a csv/tsv as factorize category type? 如何从DataFrame中的每个组中采样不同数量的行 - How to sample different number of rows from each group in DataFrame 如何将pandas数据帧保存到我可以从sql数据库的单个列中保存和检索的字符串中? - How to save a pandas dataframe into a string that i can save and retrieve from a single column in sql database? 从 pandas DataFrame 中提取单个类别的计数 - Extract count of single category from a pandas DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM