首先,我们需要使用pandas将数据读入Python中。
import pandas as pd
# Read data into dataframe
df = pd.read_csv('data.csv')
接下来,我们可以使用groupby方法按年月对数据进行分组。
# Groupby year-month
grouped = df.groupby(['Year', 'Month'])
然后,我们可以定义一个函数来查找每个组中的前N小的值列。
def find_top_n_smallest(x, n):
# Drop non-numeric columns
x = x.select_dtypes(include=['float', 'int'])
# Sort by smallest values
x = x.min().sort_values()[:n]
return x
最后,我们可以使用apply方法将函数应用于每个分组并将结果存储在新的数据框中。
# Find top N smallest values columns for each group
n = 3 # Set N value
top_n_smallest = grouped.apply(find_top_n_smallest, n=n)
# Reset index
top_n_smallest = top_n_smallest.reset_index()
# Print results
print(top_n_smallest)
输出结果将会是一个新的数据框,其中包含按年月分组的前N小值列。
参考链接:https://stackoverflow.com/questions/59634101/groupby-year-month-and-find-top-n-smallest-values-columns-in-python