Я создаю скрипт Python для управления данными в CSV-файле и возврата нового CSV-файла. Часть того, что он делает, — это расчет 10-дневной выплаты и выплата ежедневных процентов. Когда я конвертировал столбец с процентами в десятичный формат и конвертировал все целые числа в CSV в десятичные, я думал, что просто нацелен на определенные строки. (я впервые использую Python, поэтому уверен, что ответ очевиден.
import pandas as pd
# Load the CSV
df = pd.read_csv(r'file\path\csv.csv', header=None)
# Function to split names into first, middle (if present), and last
def split_name(name):
parts = name.split(' ')
first_name = parts[0] if len(parts) > 0 else ""
middle_name = parts[1] if len(parts) > 2 else ""
last_name = parts[2] if len(parts) > 2 else parts[1] if len(parts) == 2 else ""
return pd.Series([first_name, middle_name, last_name])
# Apply the function to the fourth column (D)
df[['FirstName', 'MiddleName', 'LastName']] = df[3].apply(split_name)
# Assign the split names to the desired columns (D First, E Middle, F Last)
df[3] = df['FirstName']
df[4] = df['MiddleName']
df[5] = df['LastName']
# Copy Last 4 of the account number from column AO to A
df[0] = df[40].astype(str).str[-4:]
#copy the last char of the city state from column I to J
df[9] = df[8].astype(str).str[-2:]
#Delete the last two char of I to remove the State
df[8] = df[8].astype(str).str[:-3]
#configure decimal columns for integer math
df[41] = df[41].str.replace('%', '').astype(float)
df[21] = df[21].astype(str).str.replace('$', '', regex=False).astype(str)
df[21] = df[21].astype(str).str.replace(',', '').astype(str)
df[21] = df[21].astype(float)
#calculate daily interest
df[31] = (df[21] * df[41] / 100) / 365
df = df.round({31: 2})
#fix date column to 4 digit
#df[14] = df[14].astype(str).str[:4]
# Drop the temporary columns
df.drop(['FirstName', 'MiddleName', 'LastName'], axis=1, inplace=True)
df.drop([41], axis=1, inplace=True)
# Save the updated CSV file
df.to_csv(r'file\path\New.csv', index=False, header=None)
Подробнее здесь: https://stackoverflow.com/questions/792 ... csv-in-pyt
Необходимость сделать определенные столбцы десятичными, не затрагивая весь CSV в Python. ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение