gpt4 book ai didi

python - 仅读取一个数据帧中的数值并根据这些值创建另一个数据帧

转载 作者:行者123 更新时间:2023-12-01 01:08:01 26 4
gpt4 key购买 nike

我已将 Excel 导入到数据框中,它看起来像这样:

rule_id  reqid1 reqid2  reqid3
50014 1.0 0.0 1.0
50238 0.0 1.0 0.0
50239 0.0 1.0 0.0
50356 0.0 0.0 1.0
50412 0.0 0.0 1.0
51181 0.0 1.0 0.0
53139 0.0 0.0 1.0

然后我编写了这段代码来比较相应的 reqid,然后删除 reqid 列:

    m = df1.eq(df1.shift(-1, axis=1))

arr1 = np.select([df1 ==0, m], [np.nan, 1], 1*100)

dft4 = pd.DataFrame(arr1, index=df1.index).rename(columns=lambda x: 'comp{}'.format(x+1))

dft5 = df1.join(dft4)
cols = [c for c in dft5.columns if 'reqid' in c]
df8 = dft5.drop(cols, axis=1)

结果如下:

enter image description here

然后我将其转置,数据如下所示:

enter image description here

现在我想将此数据写入一个单独的数据帧,其中仅存在数值并删除空值或空值。数据框应如下所示:

enter image description here

如果有人能帮助我,我将不胜感激。

最佳答案

使用justify函数,然后仅删除 NaNs 行 DataFrame.dropna带参数how='all':

df8 = dft5.drop(cols, axis=1).T
<小时/>
df8 = pd.DataFrame(justify(df8.values,
invalid_val=np.nan,
axis=0,side='up'), columns=df8.columns).dropna(how='all')
print (df8)
rule_id 50014 50238 50239 50356 50412 51181 53139
0 100.0 100.0 100.0 100.0 100.0 100.0 100.0
1 100.0 NaN NaN NaN NaN NaN NaN

另一个 Pandas 解决方案:

df8 = df8.apply(lambda x: pd.Series(x.dropna().values))
print (df8)

rule_id 50014 50238 50239 50356 50412 51181 53139
0 100.0 100.0 100.0 100.0 100.0 100.0 100.0
1 100.0 NaN NaN NaN NaN NaN NaN

关于python - 仅读取一个数据帧中的数值并根据这些值创建另一个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55142252/

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