dataframe中的ctime列的字符串为2020 02 02,如何删掉第二个空格后的数
时间: 2023-11-22 18:53:41 浏览: 36
可以使用字符串的切片操作和字符串的替换操作来实现。
首先,使用切片操作获取第一个空格之前的字符串:
```python
time_str = "2020 02 02"
first_space_index = time_str.index(" ")
new_time_str = time_str[:first_space_index]
```
然后,使用字符串的替换操作将第二个空格及其后面的字符替换为空格,即可完成删除:
```python
new_time_str = new_time_str + time_str[first_space_index+1:].replace(" ", "")
```
完整代码示例:
```python
import pandas as pd
# 创建一个包含ctime列的dataframe
df = pd.DataFrame({'ctime': ['2020 02 02', '2020 03 04', '2020 05 06']})
# 删掉第二个空格后的数
df['ctime'] = df['ctime'].apply(lambda x: x[:x.index(" ")] + x[x.index(" ")+1:].replace(" ", ""))
print(df)
```
输出结果:
```
ctime
0 2020 0202
1 2020 0304
2 2020 0506
```
相关问题
python将dataframe中的一列字符串转换为数字、
可以使用 Pandas 库中的 astype() 方法将 DataFrame 中的一列字符串转换为数字,具体方式如下:
假设需要将 DataFrame 中的 'col_name' 列转换为数字:
```python
import pandas as pd
# 创建 DataFrame
df = pd.DataFrame({'col_name': ['1', '2', '3']})
# 将 'col_name' 列转换为数字
df['col_name'] = df['col_name'].astype(int)
# 输出 DataFrame
print(df)
```
运行结果如下:
```
col_name
0 1
1 2
2 3
```
可以看到,'col_name' 列已经被成功转换为了数字类型。除了 int 类型,还可以使用 float 类型等其他类型进行转换。
dataframe 多个列字符串 单引号和中括号 去掉
假设你的 DataFrame 名称为 df,多个列名为 col1,col2,col3,其中包含单引号和中括号,可以使用字符串的 replace() 方法来去掉这些字符,示例如下:
```python
df['col1'] = df['col1'].str.replace("'", "").str.replace("[", "").str.replace("]", "")
df['col2'] = df['col2'].str.replace("'", "").str.replace("[", "").str.replace("]", "")
df['col3'] = df['col3'].str.replace("'", "").str.replace("[", "").str.replace("]", "")
```
这里使用了多次 replace() 方法,分别替换掉单引号和中括号。如果你的列名更多,可以使用循环来简化代码。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)