[英]Pandas fill empty column names with previous value
Newbie here.新手来了Try to clean up the following column name presented尝试清理呈现的以下列名称
1992 | Unnamed: 2 | Unnamed: 3 | 1993 | Unnamed: 4| Unnamed: 5| 1994 | ... | 2015 | Unnamed: 22 | Unnamed: 23|
Next column is下一栏是
Male | Female | Population | Male | Female | Population ....
Then, the row and beyond are to do with each country's populations然后,这一行及以后与每个国家的人口有关
I try the following to clean up all the unnamed column names我尝试以下方法来清理所有未命名的列名
df.columns = map(lambda x: np.nan if (re.search(r'\bUnnamed:\s\d{1,2}\b', x)) else x, df.columns)
Then I wanted to naively do a fillna function with pad method...然后我想用pad方法天真地做一个fillna函数......
df_column_names = df_column_names.fillna(method='pad')
obviously that didn't work显然那没有用
Should I just extract the column name, manipulate it as dataframe and use the fillna(method='pad')
and then just magically merge it back with the working dataframe?我是否应该只提取列名,将其作为数据fillna(method='pad')
操作并使用fillna(method='pad')
然后神奇地将其与工作数据fillna(method='pad')
合并回来?
Seems to be very clunky way to do it.似乎是非常笨拙的方法。
I think i have an answer.我想我有答案了。 My solution is to convert df.columns above as pd.Series, then run fillna(method='pad) function.我的解决方案是将上面的 df.columns 转换为 pd.Series,然后运行 fillna(method='pad) 函数。 As a result, all NaN will be populated with the precedent year value因此,所有 NaN 都将填充上一个年份值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.