gpt4 book ai didi

python - Pandas - 从每一行中删除前导零和尾随零

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:33 25 4
gpt4 key购买 nike

我想在我的 df 中按行删除前面的和试验的零值,然后让它们移动到“对齐”。

下面的例子可能是最好的证明。

初始 df:

index c1 c2 c3 c4 c5 c6 c7 c8
1 0 0 1 2 3 4 5 0
2 0 0 0 1 2 3 4 5
3 0 1 2 3 0 0 0 0
4 0 0 1 2 3 4 0 0
5 1 2 3 4 5 6 7 0
6 0 0 0 1 0 0 4 0

输出:

index c1 c2 c3 c4 c5 c6 c7
1 1 2 3 4 5
2 1 2 3 4 5
3 1 2 3
4 1 2 3 4
5 1 2 3 4 5 6 7
6 1 0 0 4

请注意,真值的“字符串”中可能有零,因此需要在第一次/反向第一次出现时停止。这可能吗?谢谢。

最佳答案

使用 np.trim_zeros :

Trim the leading and/or trailing zeros from a 1-D array or sequence.

out = pd.DataFrame([np.trim_zeros(i) for i in df.values], index=df.index)
out.columns = df.columns[:len(out.columns)]

c1 c2 c3 c4 c5 c6 c7
index
1 1 2 3 4.0 5.0 NaN NaN
2 1 2 3 4.0 5.0 NaN NaN
3 1 2 3 NaN NaN NaN NaN
4 1 2 3 4.0 NaN NaN NaN
5 1 2 3 4.0 5.0 6.0 7.0
6 1 0 0 4.0 NaN NaN NaN

关于python - Pandas - 从每一行中删除前导零和尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51867012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com