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

Python 通过在其他列中选择字符串的一部分在Pandas中创建新列,python,pandas,Python,Pandas,我有很多在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

我有很多在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秒或更短,所以我想创建一个列,其中只有秒作为float。要做到这一点,我需要选择位置6结束,并使其成为一个浮动,我可以为第一行这样做:

float(df['TimeCodes'][0][6:])
这很好,但如果我现在想创建一个全新的列“Time_sec”,以下内容不起作用:

df['Time_sec'] = float(df['TimeCodes'][:][6:])
 df['Time_sec'] = float(df['TimeCodes'][:,6:])
因为df['TimeCodes'][:][6:]将第6行移到最后一行,而我希望在每一行中的第6行移到最后一行。此外,这也不起作用:

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

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

您可以使用
slice
string方法,然后将整个内容转换为浮点:

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:][/code>不起作用,这最终会链接一些选择。首先,您抓取与
TimeCodes
列关联的
pd.Series
,然后使用
[:]
从序列中选择所有项目,然后使用
[6:://code>

选择索引为6或更高的项目。您可以使用
slice
string方法,然后将整个内容转换为浮点:

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:][/code>不起作用,这最终会链接一些选择。首先,您抓取与
TimeCodes
列关联的
pd.Series
,然后使用
[:]
从序列中选择所有项目,然后使用
[6:://code>解决方案选择索引为6或更高的项目,并通过以下方式强制转换为
浮动

解决方案-并通过以下方式将其浇铸到
float