赞
踩
目录
- df_label = pd.DataFrame(np.arange(16).reshape(4, 4), columns=list('wxyz'))
-
- data_col=df_label['w'] # 选择表格中的'w'列,使用类字典属性,返回的是Series类型
- print(data_col.max())
- df_label.to_csv(to_dir + '/label.csv', index=False)
1,按照位置:
- import pandas as pd
-
- data = pd.read_csv()
-
- data = data.iloc[:, 0:3] # 按位置取某几列
2,按照指定列名:
- import pandas as pd
- df=pd.read_excel("职位明细329.xlsx")
-
- df1 = df[['用户ID','职位ID']]
原文链接:https://blog.csdn.net/lb521200200/article/details/123829793
- import pandas as pd
-
- from numpy.random import randint
-
- df = pd.DataFrame(columns=list('abcdefghij'))
-
- columns= list(df.columns.values)
-
'运行
# 创建字典
dict = {"A":1, "B":2, "C":3} # 其中ABC为原数据,123为替换数据
# 替换
pd['替换列'] = pd['替换列'].replace(dict) # '替换列'为需要替换列字段
- def get_path(path):
- if 'imgs' in path:
- return os.path.dirname(label_file) + path
- else:
- return path
- df_label = pd.read_csv(label_file)
-
- columns= list(df_label.columns.values)
-
- if dtype == "train":
- data = df_label[(df_label['is_train'] == 1)]
- else:
- data = df_label[(df_label['is_train'] == 0)]
- imgs = data[columns[0]].apply(get_path)
-
- self.imgs.extend(imgs.values.tolist())
- id1_s=data[columns[1]]
- self.id1_s.extend(id1_s.values.astype(np.int64))
- import pandas as pd
-
- df_label= pd.read_csv('tf.csv', header=None, names=['a', 'b', 'c'])
-
- df_label.loc[1] = ["related_path", 0, 0]
- df_label.to_csv('tf.csv', index=False)
- df_label = pd.read_csv('tf.csv', header=None, names=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'])
- df_label.to_csv('tf.csv', index=False)
- filtered_df = df[df['name'].notnull()]
- filtered_df = df[df['name'].isnull()]
- import os
-
- import pandas as pd
-
- if __name__ == '__main__':
-
- df_train=pd.read_csv("aaa.csv")
- #可以修改csv文件数据
- for index, row in df_train.iterrows():
- row['asdf']=12345
- row[2]=222
-
- df_train.to_csv("aaa.csv", index=False)
-
- import os
-
- import pandas as pd
-
- if __name__ == '__main__':
-
- df_train=pd.read_csv("aaa.csv")
-
- data = df_train[(df_train['wer'] == 222)] #筛选
- data['asdf'] = 11111 #不能保存到csv文件
- data.to_csv("aaa.csv", index=False)
- label_file=r'D:\\label.csv'
- df_label = pd.read_csv(label_file)
-
- start=time.time()
- col_names = df_label.columns.tolist()
-
- to_col=col_names[1]
-
- df_label.loc[(df_label['size'] == 1) & (df_label[to_col]==2), [to_col]]=3
-
- df_label.loc[(df_label['size'] == 0) & (df_label[to_col] == 3), [to_col]] = 2
- df_label.to_csv(label_to_file, index=False)
-
- print('time',time.time()-start)
- import pandas as pd
-
- label_file=r'F:\label.csv'
- df_label = pd.read_csv(label_file)
- col_names = df_label.columns.tolist() # 将数据框的列名全部提取出来存放在列表里
- if 'box' not in col_names:
- col_names.append('box')
- df_label = pd.read_csv(label_file, header=None, names=col_names)
- df_label.to_csv(label_file, index=False)
- df_label = pd.read_csv(label_file)
-
- data_none = df_label[df_label["box"].isnull()]
-
- for index,data_n in data_none.iterrows():
- img_path=data_n[col_names[0]]
- if img_path.endswith(".jpg"):
- tmp_dir = r'F:\project\shida\not_found'
- img_path_all = os.path.dirname(label_file) + img_path
- shutil.copy(img_path_all, tmp_dir)
注意:df_label.img_path
是直接选择列名,不用加引号""筛选。
- df_label.loc[(df_label.img_path == img_path), 'box'] = box
- df_label.loc[(df_label.img_path == img_path), col_names[1]] = new_index
- data = df_label[(df_label["img_path"] == img_path)]
- if data.size>0:
- if data.shape[0]>1:
- print('err',img_path)
- import os.path
-
- if __name__ == '__main__':
-
- import pandas as pd
-
- label_file=r'F:\project\shida\small\label.csv'
- df_label = pd.read_csv(label_file)
- col_names = df_label.columns.tolist() # 将数据框的列名全部提取出来存放在列表里
- if 'box' not in col_names:
- col_names.append('box')
- df_label = pd.read_csv(label_file, header=None, names=col_names)
- df_label.to_csv(label_file, index=False)
- df_label = pd.read_csv(label_file)
-
- data_path=r'F:\project\shida\small\val_clf_size_2.txt'
- with open(data_path ,'r') as f_r:
- lines =f_r.readlines()
- for line in lines:
- line_data= line.split(' ')
- img_path=line_data[0]
- img_path='/imgs/'+os.path.basename(img_path)
- box=line_data[1]
- id=int(line_data[2])
-
- data = df_label[(df_label["img_path"] == img_path)]
- if data.size>0:
- if data.shape[0]>1:
- print('err',img_path)
- exit(435)
- index=int(data[col_names[1]])
- new_index=0
- if index in [1,2]:
- new_index=index-1
- else:
- new_index = id+2
- df_label.loc[(df_label.img_path == img_path), 'box'] = box
- df_label.loc[(df_label.img_path == img_path), col_names[1]] = new_index
- else:
- print('not found',img_path)
-
-
-
-
- # df_label.loc[1] = ["related_path", 0, 0, 0]
- df_label.to_csv(label_file, index=False)
- df_label = pd.read_csv(label_file)
- col_names = df_label.columns.tolist() # 将数据框的列名全部提取出来存放在列表里
-
-
-
- if 'box' not in col_names:
- df_label.insert(loc=len(col_names), column='box', value='')
pandas为DataFrame格式数据添加新列的方法非常简单,只需要新建一个列索引,再为其赋值即可。
以path分组,左边一组,右边一组
-
- import pandas as pd
- import numpy as np
- df = pd.DataFrame(columns=['123','111','path','222'],data=[[1,2,3,4]])
-
- split_col='path'
-
- column_np=df.columns.values
-
- np_index=np.where(column_np==split_col)[0][0]
-
- print("np_index",np_index)
-
- columns=df.columns.values.tolist()
- a_index=columns.index(split_col)
-
- print("a_index",a_index)
-
- for index,row in df.iterrows():
-
- data=row.values[1:np_index]
- print('data',data)
'运行
结果:
np_index 2
a_index 2
data [2]
注意:data必须是行列组成,如果[[1,2,3,]]
首先,创建一个DataFrame结构数据,作为数据举例。
- import pandas as pd
- # 创建一个DataFrame结构数据
- data = {'a': ['a0', 'a1', 'a2'],
- 'b': ['b0', 'b1', 'b2']}
- df = pd.DataFrame(data)
- print('举例数据情况:\n', df)
添加新列的方法,如下:
一、insert()函数
语法:
DataFrame.insert(loc, column, value,allow_duplicates = False)
参数 说明
loc 必要字段,int类型数据,表示插入新列的列位置,原来在该位置的列将向右移。
column 必要字段,插入新列的列名。
value 必要字段,新列插入的值。如果仅提供一个值,将为所有行设置相同的值。可以是int,string,float等,甚至可以是series /值列表。
allow_duplicates 布尔值,用于检查是否存在具有相同名称的列。默认为False,不允许与已有的列名重复。
实例:插入c列
df.insert(loc=2, column='c', value=3) # 在最后一列后,插入值全为3的c列
print('插入c列:\n', df)
1
2
二、直接赋值法
语法:df[‘新列名’]=新列的值
实例:插入d列
df['d'] = [1, 2, 3] # 插入值为[1,2,3]的d列
print('插入d列:\n', df)
1
2
注:该方法不可以选择插入新列的位置,默认为最后一列。如果新增的一列值相同,直接为其赋值一个常量即可;如果插入值不同,为列表格式,需与已有列的行数长度一致,如举例中原来列为3行,新增列也必须有3个值。
三、reindex()函数
语法:df.reindex(columns=[原来所有的列名,新增列名],fill_value=值)
reindex()函数用法较多,此处只是针对添加新列的用法
实例:插入e列
df1 = df.reindex(columns=['a', 'b', 'c', 'd', 'e']) # 不加fill_value参数,默认值为Nan
df2 = df.reindex(columns=['a', 'b', 'c', 'd', 'e'], fill_value=1) # 加入fill_value参数,填充值为1
print('插入e列(不加fill_value参数):\n', df1)
print('插入e列(加fill_value参数):\n', df2)
1
2
3
4
注:该方法需要把原有的列名和新列名都加上,如果列名过多,就比较麻烦。
四、concat()函数
原理:利用拼接的方式,添加新的一列。好处是可以同时新增多个列名。
concat()函数用法较多,此处只是针对添加新列的用法
实例:插入f列
df1 = pd.concat([df1, pd.DataFrame(columns=['f'])])
print('插入f列:\n', df1)
1
2
五、loc()函数
原理:利用loc的行列索引标签来实现。
语法:df.loc[:,新列名]=值
实例:插入g列
df1.loc[:, 'g'] = 0
print('插入g列:\n', df1)
1
2
以上就是pandas添加新列的5种常见用法。
————————————————
版权声明:本文为CSDN博主「一位代码」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/LHJCSDNYL/article/details/124577994
- import csv
- import random
- import string
-
- # 随机生成字符串的函数
- def random_string(length):
- letters = string.ascii_lowercase
- return ''.join(random.choice(letters) for i in range(length))
-
- # 打开文件并写入数据
- with open('output.csv', 'w', newline='') as f:
- writer = csv.writer(f, lineterminator='\r\n')
- writer.writerow(['Column 1'.ljust(18), 'Column 2'.ljust(18), 'Column 3'.ljust(18), 'Column 4'.ljust(18)]) # 写入标题行
- for i in range(20): # 生成20行数据
- row = [random_string(random.randint(5, 15)).ljust(18) for _ in range(4)] # 每行包含4个随机长度(5到15之间)的字符串
- writer.writerow(row)
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。