社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

编写Python代码以使用条件语句从现有列创建新的CSV列

sneha • 5 年前 • 1610 次点击  

我对Python编码很新,希望根据现有列的条件语句创建一个新列。

我使用Python2.7版本并在CentOs上运行代码。

import pandas as pd                                                     
file1 = pd.read_csv("/root/Documents/temp_file_{}.csv".format(timestr))
file1['FileName'] = ''
file1['FileName'] = file1['FileType'].apply(lambda x: df['Path'].str.extract('[^/]+$', expand=False) if x=='f' else '')
file1.to_csv('/root/Documents/temp1_file_{}.csv'.format(timestr),index = False)

下面是我的CSV文件:

FileType,Path

d,/

f,/documents/csv/.zip

d,/documents/images

d,/hive/28374849

f,/hadoop/jdjdjd/dnejfn.img

必需的CSV文件:

FileType,Path,FileName

d,/,

f,/documents/csv/.zip,.zip

d,/documents/images,

d,/hive/28374849,

f,/hadoop/jdjdjd/dnejfn.img,dnejfn.img

我想创建一个新的列文件名,只有当列文件类型为“f”时,才能从路径列中提取该列中的数据,否则该列中的数据应为空值或没有数据

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49803
 
1610 次点击  
文章 [ 2 ]  |  最新文章 5 年前
ashish14
Reply   •   1 楼
ashish14    6 年前

尝试使用此方法从路径中获取最后一部分。将字符串从最右边的一方拆分为“/”作为分隔符,并使用负索引获取最后一个元素(基本上是文件名):


file1['FileName'] = ''
file1['FileName'] = file1.apply(lambda x: x['Path'].rsplit("/", 1)[-1]  if x["FileType"]=='f' else '' , axis=1)

file1

FileType    Path    FileName
0   d   /   
1   f   /documents/csv/.zip .zip
2   d   /documents/images   
3   d   /hive/28374849  
4   f   /hadoop/jdjdjd/dnejfn.img   dnejfn.img

由于矢量化,使用比apply函数快的numpy:

file1['FileName'] = np.where(file1["FileType"]=='f', file1['Path'].str.rsplit("/", n=1).str[-1], '')

FileType    Path    FileName
0   d   /   
1   f   /documents/csv/.zip .zip
2   d   /documents/images   
3   d   /hive/28374849  
4   f   /hadoop/jdjdjd/dnejfn.img   dnejfn.img

Chris
Reply   •   2 楼
Chris    6 年前

使用 numpy.where 具有 pandas.Series.str.rsplit :

import numpy as np
import pandas as pd

df['FileName'] = np.where(df['FileType'].eq('f'),df['Path'].str.rsplit('/').str.get(-1), '')

输出:

  FileType                       Path    FileName
0        d                          /            
1        f        /documents/csv/.zip        .zip
2        d          /documents/images            
3        d             /hive/28374849            
4        f  /hadoop/jdjdjd/dnejfn.img  dnejfn.img