【问题标题】:Sort dataframe by month and find the first non-zero value in each column for each month按月对数据帧进行排序,并在每个月的每列中找到第一个非零值
【发布时间】:2020-05-29 18:16:07
【问题描述】:

我需要将包含 200 列的 CSV(第一列是日期)加载到 python 中的 pandas 数据框中。我需要对数据进行排序并返回每个月的第一个非零值。我应该制作单独的数据框还是每个月,然后搜索?解决这个问题的最佳方法是什么?

df = pd.read_csv('loaddata.csv')
df['DATE'] = pd.to_datetime(df['DATE'], format='%m/%d/%Y')
df['Month']= pd.DatetimeIndex(df['DATE']).month


THe data looks like this:

Date    Data_1   Data_2  Data_3
1/d/y    0         0       1
2/d/y    0         1       2
3/d/y    2         6       0
1/d/y    5         3       45
2/d/y    20        7       90
3/d/y    25        12      18


Returns: 
      Data_1   Data_2   Data_3
Jan     5         3       1
Feb     20        7       2
Mar     2         6       18

【问题讨论】:

  • 每列每个月的第一个非零值还是什么?请尽量说清楚一点。

标签: python pandas dataframe datetime pandas-groupby


【解决方案1】:

FebData_2 列出现错误:第一个非零是 1,而不是 7。


这是一种方法:

def first_non_zero(col):
    """Return the first non-zero value of a column, or nan if the column is all-zero"""
    head = col[col != 0].head(1)
    return np.nan if head.empty else head.values

df.groupby('Month').apply(lambda group: group[['Data_1', 'Data_2', 'Data_3']].apply(first_non_zero)) \
    .reset_index(level=1, drop=True)

结果:

       Data_1  Data_2  Data_3
Month                        
1           5       3       1
2          20       1       2
3           2       6      18

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-09
    • 2018-08-02
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2018-04-26
    • 2014-09-13
    • 2015-05-20
    相关资源
    最近更新 更多