通过在其他列中选择字符串的一部分在Pandas中创建新列

2024-09-20 22:59:44 发布

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

我有很多用Matlab编程的经验,现在用Python编程,我就是搞不懂这个东西。。。我有一个数据帧,其中包含一列时间代码,如00:00:00.033。在

timecodes = ['00:00:01.001', '00:00:03.201', '00:00:09.231', '00:00:11.301', '00:00:20.601', '00:00:31.231', '00:00:90.441', '00:00:91.301']
df = pd.DataFrame(timecodes, columns=['TimeCodes'])

我所有的输入都是90秒或更少,所以我想创建一个只以秒为浮点的列。为此,我需要选择位置6结束并使其成为一个浮动,我可以对第一行进行如下操作:

^{pr2}$

这很好用,但如果我现在想创建一个全新的列“Time_sec”,则以下操作不起作用:

df['Time_sec'] = float(df['TimeCodes'][:][6:])

因为df['TimeCodes'][:][6:]将第6行移到最后一行,而我希望在每一行中从第6行到最后一行。这也不起作用:

 df['Time_sec'] = float(df['TimeCodes'][:,6:])

我需要绕一圈吗?一定有更好的办法。。。为什么df['TimeCodes'][:][6:]不起作用?在


Tags: columns数据代码dataframedftime编程时间
2条回答

您可以使用slicestring方法,然后将整个内容转换为float:

In [13]: df["TimeCodes"].str.slice(6).astype(float)
Out[13]:
0     1.001
1     3.201
2     9.231
3    11.301
4    20.601
5    31.231
6    90.441
7    91.301
Name: TimeCodes, dtype: float64

至于为什么df['TimeCodes'][:][6:]不起作用,它最终要做的是链接一些选择。首先获取与TimeCodes列相关联的pd.Series,然后从带有[:]的序列中选择所有项,然后使用[6:]选择索引为6或更高的项。在

解决方案-indexing with str并由^{}转换成{}:

print (df["TimeCodes"].str[6:])
0    01.001
1    03.201
2    09.231
3    11.301
4    20.601
5    31.231
6    90.441
7    91.301
Name: TimeCodes, dtype: object

df['new'] = df["TimeCodes"].str[6:].astype(float)
print (df)
      TimeCodes     new
0  00:00:01.001   1.001
1  00:00:03.201   3.201
2  00:00:09.231   9.231
3  00:00:11.301  11.301
4  00:00:20.601  20.601
5  00:00:31.231  31.231
6  00:00:90.441  90.441
7  00:00:91.301  91.301

相关问题 更多 >

    热门问题