处理数据框中类似数字范围的数据
Dealing with numeric range-like data in a dataframe
我有一个数据框,其值类似于 1,362 - 2,037
,首先,我该如何清理它们?比如获取这两个数字的 mean (10 - 20
➡ 15
),normalizing 或者其他什么?其次,如何删除所有行中 1,362
到 1362
中的逗号?
目前拥有:
col1
col2
col3
Yes
579
402 - 1,120
No
1,082
1,361 - 2,037
预期输出:
(均值、归一化等)
col1
col2
col3
Yes
579
761
No
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
我有一个数据框,其值类似于 1,362 - 2,037
,首先,我该如何清理它们?比如获取这两个数字的 mean (10 - 20
➡ 15
),normalizing 或者其他什么?其次,如何删除所有行中 1,362
到 1362
中的逗号?
目前拥有:
col1 | col2 | col3 |
---|---|---|
Yes | 579 | 402 - 1,120 |
No | 1,082 | 1,361 - 2,037 |
预期输出:
(均值、归一化等)
col1 | col2 | col3 |
---|---|---|
Yes | 579 | 761 |
No | 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