如何转换包含字符串(如“4:20”)的列中的数据

2024-10-01 09:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的数据框中,有一列包含如下值:

 PowerPlayTimeOnIce
       0:05
       0:05
       1:24
       3:29
       1:34
        0
       0:05
        0
        0

如何将这些转换为浮点数?你知道吗

此方法无效:

df["powerPlayTimeOnIce"] = df["powerPlayTimeOnIce"].astype('float')

你知道吗编辑:更新的数据示例为了更好地解决问题


Tags: 数据方法编辑示例dffloat浮点数astype
3条回答

你可以这样做:

import pandas as pd

data = ['0:05',
        '0:05',
        '1:24',
        '3:29',
        '1:34',
        '0:05']


def convert(s):
    minutes, seconds = map(int, s.split(":"))
    return 60 * minutes + seconds


df = pd.DataFrame(data=data, columns=['powerPlayTimeOnIce'])
print(df['powerPlayTimeOnIce'].apply(convert))

输出

0      5
1      5
2     84
3    209
4     94
5      5
Name: powerPlayTimeOnIce, dtype: int64

如果你想要一个非常详细的流,你没有一个巨大的数据集。你可以做:

df[['min', 'sec']] = df['powerPlayTimeOnIce'].str.split(':', expand=True)

df[['min'] = df[['min'].astype('int')
df['sec'] = df['sec'].apply(lambda x: float('0.'+x), axis=1)

df['diff_in_seconds'] = df['min']/60 + df['sec']

所以我把你的数据分为分钟和秒。从那里你可以转向任何形式。你知道吗

使用to_datetime

s=pd.to_datetime(df.PowerPlayTimeOnIce,format='%M:%S')
s.dt.minute*60+s.dt.second
Out[881]: 
0      5
1      5
2     84
3    209
4     94
5      5
Name: PowerPlayTimeOnIce, dtype: int64

更新

s=pd.to_datetime(df.PowerPlayTimeOnIce,format='%M:%S',errors='coerce')

(s.dt.minute*60+s.dt.second).fillna(0)
Out[886]: 
0      5.0
1      5.0
2     84.0
3    209.0
4     94.0
5      5.0
6      0.0
Name: PowerPlayTimeOnIce, dtype: float64

数据输入

  PowerPlayTimeOnIce
0               0:05
1               0:05
2               1:24
3               3:29
4               1:34
5               0:05
6                  0

相关问题 更多 >