我有一个包含以下内容的.csv文件
我希望能够生成一个.csv,其中包含一列以显示长颈鹿<;4位数字>;当该模式在“文本”列中可用时
到目前为止,我已经编写了下面的代码,它没有动态地/为每一行计算切片开始和结束索引(对于长颈鹿_编号)
import pandas as pd
file_path = 'test.csv'
data = pd.read_csv(file_path)
sub = "giraffe"
# column to identify if Giraffe is present
data['Giraffe_Present'] = data['text'].str.contains(sub)
# column to identify index of Giraffe in text
data["Giraffe_Index"] = data['text'].str.find(sub)
# column to identify starting position for slice
data['Giraffe_start'] = data['Giraffe_Index'].apply(lambda row: row)
# column to identify ending position for slice
data['Giraffe_end'] = data['Giraffe_Index'].apply(lambda row: row+11)
# column to store sliced Giraffe number from text
data['Giraffe_numbers'] = data['text'].apply(lambda row: row[data['Giraffe_Index'].apply(lambda row: row).max():data['Giraffe_Index'].apply(lambda row: row+11).max()])
print(data)
这是输出。结果对#2、#4和#5有偏差,因为长颈鹿#u数使用与#1对应的开始和结束索引
与其使用多个步骤,为什么不一次完成所有工作
我知道这不是你所期望的,但可能会很有趣
输入数据:
在字符串中查找动物和数字:
使用
animal
、start
、end
和number
列构建数据帧:合并
df
和df1
:相关问题 更多 >
编程相关推荐