python 提取多个字段其中一个字段后6位新增成列
时间: 2024-05-08 15:19:32 浏览: 16
可以使用 pandas 库中的 apply 函数来实现,示例代码如下:
```python
import pandas as pd
# 假设原始数据中有三个字段:A、B、C
data = {'A': ['abc123', 'def456', 'ghi789'], 'B': [1, 2, 3], 'C': [True, False, True]}
df = pd.DataFrame(data)
# 定义一个函数,用于从字段 A 中提取后 6 位
def extract_last_six(x):
return x[-6:]
# 使用 apply 函数创建一个新列 D,其中每个元素都是字段 A 中后 6 位
df['D'] = df['A'].apply(extract_last_six)
# 输出结果
print(df)
```
运行结果如下:
```
A B C D
0 abc123 1 True bc123
1 def456 2 False ef456
2 ghi789 3 True hi789
```
希望能够帮到你!如果还有其它问题,请直接问我哦~
相关问题
python中两个dataframe左关联后新增一列表名是否有关联的字段
可以在左关联的结果 DataFrame 中新增一列指示是否有关联的字段。具体操作步骤如下:
假设左关联后的结果 DataFrame 为 result,其中关联列为 key。
1. 使用 isna() 函数获取关联列是否为空的布尔值:
```
is_related = result['key'].notna()
```
2. 将布尔值转换为整数 0 或 1,表示是否有关联:
```
is_related = is_related.astype(int)
```
3. 将关联结果添加到 DataFrame 中:
```
result['is_related'] = is_related
```
这样,左关联后的结果 DataFrame 中就会新增一列名为 is_related,表示是否有关联的字段。其中,如果关联列 key 为空,则该行 is_related 列对应的值为 0,否则为 1。
python筛选excel某一列以多个特定字段开头
可以使用pandas库来筛选excel某一列以多个特定字段开头的数据,具体代码如下:
```python
import pandas as pd
# 读取excel文件
df = pd.read_excel('your_excel_file.xlsx')
# 筛选以'A'或'B'开头的数据
result = df[df['column_name'].str.startswith(('A', 'B'))]
# 输出结果
print(result)
```
其中,`column_name`是你要筛选的列名,`('A', 'B')`是以哪些特定字段开头的条件。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)