处理数据框中的数值范围之类的数据 [英] Dealing with numeric range-like data in a dataframe

查看:46
本文介绍了处理数据框中的数值范围之类的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,其值类似于 1,362-2,037 ,首先,如何清理它们?例如获得这两个数字的平均值( 10-20 15 ),归一化还是其他?第二,如何删除所有行中 1,362 1362 中的逗号?

I have a dataframe that has values like 1,362 - 2,037, first, how can I clean them? like getting the mean of these two numbers (10 - 2015), normalizing them or anything else? second, how can I remove the comma in 1,362 to 1362 in all rows?

<身体>
col1 col2 col3
579 402-1,120
1,082 1,361-2,037

预期输出:

(均值,归一化等)

Expected Output:

(mean, normalization, etc.)

<身体>
col1 col2 col3
579 761
1082 1699

数据框的形状:

df = pd.read_csv("/content/cleanedNASA.csv")
df.describe
...
> [31 rows x 9 columns]

谢谢.

推荐答案

df['y'] = pd.to_numeric(df['x']
    .str.replace('[^0-9\- ]', '') # 1. remove non-(digit/dash/space) characters
    .str.split(' - ')             # 2. split by ' - '
    .explode()                    # 3. explode the lists
).mean(level=0)                   # 4. calculate average by index

df

输出:

               x     y
0    402 - 1,120   761
1            674   674
2          3,196  3196
3          1,304  1304
4            853   853
5  1,361 - 2,037  1699

这篇关于处理数据框中的数值范围之类的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆