使用python对CSV列执行简单的数学操作

2024-09-25 00:22:56 发布

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

所以我有一个CSV文件,我需要将它插入API,但其中一列是美元,我想通过乘以100将它转换为美分

这是文件

tripId,scooterId,userId,totalDuration,pickUpTime,dropOffTime,userLocationAtBooking.0,userLocationAtBooking.1,userLocationAtDropOff.0,userLocationAtDropOff.1,totalFare
18721,927,38579,45,2021-08-22 03:00:49,2021-08-22 03:45:39,24.76412,46.6493,24.76409833,46.64934,9.58
18722,434,38563,45,2021-08-22 03:01:16,2021-08-22 03:45:39,24.76412,46.64933333,24.76407,46.64933333,13.53
18723,876,38554,33,2021-08-22 03:05:57,2021-08-22 03:38:55,24.71392833,46.660645,24.7097,46.66272,0.67
18724,476,32291,65,2021-08-22 03:14:37,2021-08-22 04:18:56,24.77137833,46.64568667,24.7722,46.64523167,32.35

我只需要做最后一栏“totalFare”的数学运算

我还是python新手,因此非常感谢您的帮助


Tags: 文件csvapi数学userid新手totaldurationtripid
1条回答
网友
1楼 · 发布于 2024-09-25 00:22:56

如果还不清楚如何执行该任务,这里有一个使用基本Python的实现

with open('file.csv', 'r') as in_file, open('result.csv', 'w') as out_file: # Open input and output files
    out_file.write(next(in_file))                # Reads header from input file and writes to output file
    for line in in_file:                         # For each line in file (we are past header line)
        line = line.rstrip().split(',')          # Create list from comma separated string
        line[-1] = f'{100*float(line[-1]):.0f}'  # Convert last item in list to float and multiply by 100
                                                 # and convert foat to stringto 0 decimal places
            
        #line[-1] = '{:.0f}'.format(100*float(line[-1])) # Alternative to above line that doesn't use
                                                         # f-string (i.e. can use in earlier versions of Python)  
        
        out_file.write(','.join(line) + '\n')    # Output updated list as comma separated string
    

输出(使用示例输入)

tripId,scooterId,userId,totalDuration,pickUpTime,dropOffTime,userLocationAtBooking.0,userLocationAtBooking.1,userLocationAtDropOff.0,userLocationAtDropOff.1,totalFare
18721,927,38579,45,2021-08-22 03:00:49,2021-08-22 03:45:39,24.76412,46.6493,24.76409833,46.64934,958
18722,434,38563,45,2021-08-22 03:01:16,2021-08-22 03:45:39,24.76412,46.64933333,24.76407,46.64933333,1353
18723,876,38554,33,2021-08-22 03:05:57,2021-08-22 03:38:55,24.71392833,46.660645,24.7097,46.66272,67
18724,476,32291,65,2021-08-22 03:14:37,2021-08-22 04:18:56,24.77137833,46.64568667,24.7722,46.64523167,3235

使用Python模块的替代方案(更短的解决方案)

import pandas as pd

df = pd.read_csv('file.csv')               # Read CSV file into Pandas DataFrame
df['totalFare'] *= 100                     # multiply total_fare by 100
df.to_csv('result.csv', index = False)     # Write to output file as csv

相关问题 更多 >