[英]Replacing the last non-nAn value to the last column of the dataframe
My current dataframe is this:我当前的数据框是这样的:
df.head()
Output:输出:
Name姓名 | Gender性别 | Country国家 | Year年 |
---|---|---|---|
Adam亚当 | Male男性 | America美国 | 1993 1993 |
Betty贝蒂 | 1968 1968年 | NaN钠 | NaN钠 |
Calvin卡尔文 | NaN钠 | 1995 1995 | NaN钠 |
Debra黛布拉 | Female女性 | 2000 2000 | NaN钠 |
I would like to shift all the last non-NaN values to the last column of the dataframe.我想将所有最后的非 NaN 值转移到数据框的最后一列。
So basically I need a code that populates this output:所以基本上我需要一个填充这个输出的代码:
Output:输出:
Name姓名 | Gender性别 | Country国家 | Year年 |
---|---|---|---|
Adam亚当 | Male男性 | America美国 | 1993 1993 |
Betty贝蒂 | NaN钠 | NaN钠 | 1968 1968年 |
Calvin卡尔文 | NaN钠 | NaN钠 | 1995 1995 |
Debra黛布拉 | Female女性 | NaN钠 | 2000 2000 |
Thank you for your help谢谢您的帮助
Use ffill
on index axis because Year
is your last column and the last valid value of a row is a year.在索引轴上使用ffill
因为Year
是您的最后一列,而行的最后一个有效值是一年。
df['Year'] = df.ffill(axis=1)['Year'].astype(int)
print(df)
# Output
Name Gender Country Year
0 Adam Male America 1993
1 Betty 1968 NaN 1968
2 Calvin NaN 1995 1995
3 Debra Female 2000 2000
To be safe, you can use pd.to_numeric
to remove values where year is not defined for a row:为了安全起见,您可以使用pd.to_numeric
删除未为行定义年份的值:
df['Year'] = pd.to_numeric(df.ffill(axis=1)['Year'], errors='coerce')
print(df)
# Output
Name Gender Country Year
0 Adam Male America 1993.0
1 Betty 1968 NaN 1968.0
2 Calvin NaN 1995 1995.0
3 Debra Female 2000 2000.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.