gpt4 book ai didi

python - 在 Pandas 数据框中将字符串 2.90K 转换为 2900 或将 5.2M 转换为 5200000

转载 作者:太空狗 更新时间:2023-10-29 20:41:45 24 4
gpt4 key购买 nike

在处理 pandas 数据框内的数据方面需要一些帮助。欢迎任何帮助。

我有 CSV 格式的 OHCLV 数据。我已将文件加载到 Pandas 数据框中。

如何将体积列从 2.90K 转换为 2900 或将 5.2M 转换为 5200000。该列可以包含以千为单位的 K 和以百万为单位的 M。

import pandas as pd

file_path = '/home/fatjoe/UCHM.csv'
df = pd.read_csv(file_path, parse_dates=[0], index_col=0)
df.columns = [
"closing_price",
"opening_price",
"high_price",
"low_price",
"volume",
"change"]

df['opening_price'] = df['closing_price']
df['opening_price'] = df['opening_price'].shift(-1)
df = df.replace('-', 0)
df = df[:-1]
print(df.head())

Console:
Date
2016-09-23 0
2016-09-22 9.60K
2016-09-21 54.20K
2016-09-20 115.30K
2016-09-19 18.90K
2016-09-16 176.10K
2016-09-15 31.60K
2016-09-14 10.00K
2016-09-13 3.20K

最佳答案

def value_to_float(x):
if type(x) == float or type(x) == int:
return x
if 'K' in x:
if len(x) > 1:
return float(x.replace('K', '')) * 1000
return 1000.0
if 'M' in x:
if len(x) > 1:
return float(x.replace('M', '')) * 1000000
return 1000000.0
if 'B' in x:
return float(x.replace('B', '')) * 1000000000
return 0.0

df['col'] = df['col'].apply(value_to_float)

关于python - 在 Pandas 数据框中将字符串 2.90K 转换为 2900 或将 5.2M 转换为 5200000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39684548/

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