简体   繁体   English

需要根据第一个非 NaN 值获取列名,并在新列中返回该列名

[英]Need to fetch column name based on first non NaN value, and return that column name in a new column

I have 12 columns, each labeled 1-12 that are representing months.我有 12 列,每列标记为 1-12,代表月份。 Some columns have a data reading, and others are blank (nan).有些列有数据读取,而其他列是空白(nan)。 I need to have a new column that displays the first month with a reading.我需要一个新列来显示第一个月的读数。 I also need another column that displays the last column with a reading.我还需要另一列显示最后一列的读数。

Right now I have tried: df['df_initial_month] = first_valid_index() In the very first column I have "ID's" that I would like to skip.现在我已经尝试过: df['df_initial_month] = first_valid_index()在第一列中,我有我想跳过的“ID”。 Right now when I run the code it just displays the first ID in every single row of the new column现在,当我运行代码时,它只会在新列的每一行中显示第一个 ID

I have also tried using df.ffill(axis=1).iloc[:,0]我也尝试过使用df.ffill(axis=1).iloc[:,0]

Define column_list to be a list containing columns names of the columns corresponding to the 12 months and then try the following: df['df_initial_month'] = df[column_list].apply(pd.DataFrame.first_valid_index, axis=1) .将 column_list 定义为包含对应于 12 个月的列的列名的列表,然后尝试以下操作: df['df_initial_month'] = df[column_list].apply(pd.DataFrame.first_valid_index, axis=1)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM