gpt4 book ai didi

python - 连接和移动 Pandas 中的列应用

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:34 24 4
gpt4 key购买 nike

我看到了一个看起来像下面示例的数据框

col_a col_b col_c col_d extra1 extra2 extra3
a a a a b c d
a a a a b c d
a a a b c d Nan
a a a b c d Nan
a a b c d Nan Nan
a a b c d Nan Nan
a b c d Nan Nan Nan
a b c d Nan Nan Nan

我必须把它改造成这样的东西:

col_a    col_b col_c col_d 
a a a a b c d
a a a a b c d
a a a b c d
a a a b c d
a a b c d
a a b c d
a b c d
a b c d

因此看起来取决于 NaN 的位置(extra1 2 或 3),我总是必须将最后 3 列移动到包含 Nan 的列之前,并将前面的列连接到 col_a 中。

最佳答案

使用:

#if necessary convert string `Nan` to missing values
df = df.replace('Nan', np.nan)

df = df.apply(lambda x: x.shift(x.isnull().sum()), axis=1)
print (df)
col_a col_b col_c col_d extra1 extra2 extra3
0 a a a a b c d
1 a a a a b c d
2 NaN a a a b c d
3 NaN a a a b c d
4 NaN NaN a a b c d
5 NaN NaN a a b c d
6 NaN NaN NaN a b c d
7 NaN NaN NaN a b c d

df1 = df.iloc[:, -3:]
df1.insert(0, 'a', df.iloc[:, :-3].add(' ').fillna('').sum(axis=1))
df1.columns = df.columns[:4]
print (df1)
col_a col_b col_c col_d
0 a a a a b c d
1 a a a a b c d
2 a a a b c d
3 a a a b c d
4 a a b c d
5 a a b c d
6 a b c d
7 a b c d

关于python - 连接和移动 Pandas 中的列应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51669383/

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