使用python解码表的内容

2024-10-03 17:23:40 发布

您现在位置:Python中文网/ 问答频道 /正文

Click here to view the image

上图是我的工作环境(如熊猫(python))

我有一个csv文件,我把csv文件的内容转换成python。你知道吗

file_path=filedialog.askopenfilename()
csv_file=open(file_path,'r')
pd.read_csv(csv_file)

现在在代码集之后,我可以在Python中以表格的形式显示它的内容。 现在我想解码一列“Batch”中的数据

在图中,您可以看到一个表,在该表中,特定的列“Batch”非常重要,它将被解码。 查看**列批次下的数据。你知道吗

第一个字符:年份

第二个字符:字母表。它映射到一个月(a-jan,B-feb,C-Mar,D-April,E-May……)

第三和第四个字符日期

例如:6B08MK1D11的生产日期为2016年2月8日。

现在我要解码列中的每个数据,根据其批次号查找其日期。在解码之后,我想创建一个新的列,在这个列中,我把不同日期的值放到一个新列中。你知道吗

例如 解码数据“6B08MK1D11”后,我得到的日期为08-02-2016。现在对于所有这些单独的批号,我将获得单独的日期,现在应该通过在同一个表中创建一个新列来放置新的日期值。你知道吗

创建新列后,日期列应按a-Z(升序)排序。你知道吗

我试着教如何给Python分配月份:比如

for everycode[1] in Bat:
    if everycode[1]=='A':
       everycode[1] = 'Jan'
    if everycode[1]=='B':
       everycode[1] = 'Feb'
    if everycode[1]=='C':
       everycode[1] = 'Mar'
    if everycode[1]=='D':
       everycode[1]= 'Apr'
    if everycode[1]=='E':
       everycode[1]= 'May'
    if everycode[1]=='F':
       everycode[1]= 'Jun'
    if everycode[1] == 'G':
       everycode[1]= 'Jul'
    if everycode[1]=='H':
       everycode[1]= 'Aug'
    if everycode[1]=='I':
       everycode[1]= 'Sep'
    if everycode[1]=='J':
       everycode[1] = 'Oct'
    if everycode[1]=='K':
       everycode[1]= 'Nov'
    if everycode[1]=='L':
       everycode[1]= 'Dec'    

但当我执行这个时,它会返回如下错误:

TypeError:'str'对象不支持项分配


Tags: 文件csv数据path内容ifherebatch
1条回答
网友
1楼 · 发布于 2024-10-03 17:23:40

你可以这样做:

df = pd.read_csv(csv_file)
df['Batch'] = df['Batch'].apply(interpret_date)

def interpret_date(code):
   _year = replace_year(code[0])
   _month = replace_month(code[1])
   _date = replace_date(code[2:4])
   return '-'.join([_date, _month, _year])

您需要编写replace_...()函数来将每个输入映射到正确的值。你知道吗

相关问题 更多 >