csv 我可以编辑列中特定字符串中的数字吗?[已关闭]

bejyjqdl  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(82)

已关闭,此问题需要更focused。它目前不接受回答。
**想改善这个问题吗?**更新问题,使其只关注editing this post的一个问题。

上个月关门了。
Improve this question
所以我试图编辑一个CSV文件(使用Pandas),作为Python的初学者,我正在努力制定如何做到这一点。
这些列称为“文件大小”,条目如下:1.0 MB 2.10 MB 12 GB 1.2 GB
我想把它转换成数字,这样我就可以根据实际大小进行比较和过滤。有人知道该怎么做吗?
我在谷歌上搜索过,但实际上并没有尝试打出任何东西,因为我完全不知道如何做到这一点。我正在寻找课程,所以如果你有任何,请让我知道!

zour9fqk

zour9fqk1#

这是你的解决方案。我用一个示例csv文件测试了这个问题,如下所示:

sizes_in_string
1.0 MB
2.10 MB
12 GB
1.2 GB
1.232 GB
2 KB
2.1 MB

下面是如何将sizes in string列转换为数字:

import pandas as pd
import re 

# This method will convert the size strings into bytes as float
def convert_to_bytes(size_str):
    size_str = size_str.lower()
    units = {'kb': 1024, 'mb': 1024 ** 2, 'gb': 1024 ** 3, 'tb': 1024 ** 4}
    
    for unit, multiplier in units.items():
        if unit in size_str:
            return int(float(size_str.replace(unit, '').strip()) * multiplier)
    
    return float(re.sub(r'[^\d]', '', size_str))

# Read CSV file into a DataFrame
df = pd.read_csv('sizes.csv')

# Apply size conversion to the 'size' column
df['size_in_bytes'] = df['sizes_in_string'].apply(convert_to_bytes)

print(df)

输出量:

sizes_in_string  size_in_bytes
0          1.0 MB        1048576
1         2.10 MB        2202009
2           12 GB    12884901888
3          1.2 GB     1288490188
4        1.232 GB     1322849927
5            2 KB           2048
6          2.1 MB        2202009

相关问题