gpt4 book ai didi

python - Pandas :如果列 'E' 的值为 'C',则更新列 'x' 的值

转载 作者:行者123 更新时间:2023-11-28 20:56:19 25 4
gpt4 key购买 nike

我有一个像这样的数据框:

           A           B       C       D  E
0 NSPNT 'ACTENRGY' 'XD01' 'DSU' F
1 NSPNT 'ACTENRGY' 'XD21' 'DSU' F
2 NSPNT 'ACTENRGY' 'XD22' 'DSU' F
3 NSPNT 'ACTENRGY' 'XD23' 'DSU' F
4 NSPNT 'ACTENRGY' 'XD24' 'DSU' F
5 NSPNT 'ACTENRGY' 'XD25' 'DSU' F
6 NSPNT 'ACTENRGY' 'XD01' 'DSU' F
7 NSPNT 'ACTENRGY' 'ACK' 'MISC' F
8 NSPNT 'ACTENRGY' 'ACU' 'MISC' F
9 NSPNT 'ACTENRGY' 'ACK' 'MISC' F
10 NSPNT 'ACTENRGY' 'ACU' 'MISC' F
11 NSPNT 'ACTENRGY' 'ACK' 'MISC' F
12 NSPNT 'ACTENRGY' 'ACU' 'MISC' F
13 NSPNT 'ACTENRGY' 'ACF' 'MISC' F
14 NSPNT 'ACTENRGY' 'ASF' 'MISC' F
15 NSPNT 'ACTENRGY' 'DEF' 'MISC' F
16 NSPNT 'ACTENRGY' 'RLR' 'RLR' T

我想要实现的是当 Column 'C' =='ACK' 使 Column 'E' = T到目前为止,我已经尝试了以下方法:

import os
import pandas as pd


source_folder = 'D:/NSSCDB/STTS_RCL_Export/'

def editNSPNT():

for somefile in os.listdir(source_folder):
if (somefile.startswith(('nsscdb_output_dts')) and
somefile.endswith(('.txt'.lower()))):

df = pd.read_csv(source_folder + somefile, encoding='utf-8', names = ['A','B','C','D','E'], header=4)
#for x in df['C']:
#if (x == 'ACK'):
#df['E'] = 'T'
#df.E = ["T" if x == "ACK" for x in df.C]
df.loc[(df.C=='ACK')]['E'] = 'T'

print(df)



def main():

editNSPNT()


if __name__== "__main__":
main()

我一直在尝试的两种方法都不起作用,有人可以告诉我我做错了什么吗?谢谢。

最佳答案

数据中的单引号是否给您带来了问题?

df.loc[df['C'] == "'ACK'",'E'] = 'T'

使用双引号,

        A           B       C       D  E
0 NSPNT 'ACTENRGY' 'XD01' 'DSU' F
1 NSPNT 'ACTENRGY' 'XD21' 'DSU' F
2 NSPNT 'ACTENRGY' 'XD22' 'DSU' F
3 NSPNT 'ACTENRGY' 'XD23' 'DSU' F
4 NSPNT 'ACTENRGY' 'XD24' 'DSU' F
5 NSPNT 'ACTENRGY' 'XD25' 'DSU' F
6 NSPNT 'ACTENRGY' 'XD01' 'DSU' F
7 NSPNT 'ACTENRGY' 'ACK' 'MISC' T
8 NSPNT 'ACTENRGY' 'ACU' 'MISC' F
9 NSPNT 'ACTENRGY' 'ACK' 'MISC' T
10 NSPNT 'ACTENRGY' 'ACU' 'MISC' F
11 NSPNT 'ACTENRGY' 'ACK' 'MISC' T
12 NSPNT 'ACTENRGY' 'ACU' 'MISC' F
13 NSPNT 'ACTENRGY' 'ACF' 'MISC' F
14 NSPNT 'ACTENRGY' 'ASF' 'MISC' F
15 NSPNT 'ACTENRGY' 'DEF' 'MISC' F
16 NSPNT 'ACTENRGY' 'RLR' 'RLR' T

关于python - Pandas :如果列 'E' 的值为 'C',则更新列 'x' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54812492/

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