首页 > 其他分享 >dataframe的构造,取值,赋值,移动,交集,并集,排序,打印,转List,导出csv

dataframe的构造,取值,赋值,移动,交集,并集,排序,打印,转List,导出csv

时间:2024-05-08 09:57:34浏览次数:19  
标签:并集 df list df1 dataframe python pd List datas

一、构造    da=pd.read_csv(filepath_or_buffer='data.csv',sep='\t')     print(da)     datas=pd.DataFrame(da) 2、直接赋值 df = pd.DataFrame([[1.4, np.nan], [7, -4], [np.nan, np.nan], [0.75, -1.3]], index=[1, 2, 3, 4],                   columns=['one', 'two'])

3、Series转换为DataFrame

一种方法是通过字典转
metric = df.loc[0][index]
metric_dict = {'metric_name':metric.index,'ereport_pie_y':metric.values}
data = pd.DataFrame(metric_dict)

另外一种直接通过Series的

to_frame()```
方法
df=metric.to_frame()

如果要index也做为一列,可以用
df = df.reset_index()

二、读值     # 第2行第2列     ds =datas.ix[[1]].values[0][1]     ds = datas.loc[1, 'open']

    #取第二行

    ds = datas.loc[2]     # 名为“open"的列     ds = datas["open"]     # 选取open列大于4的     ds = datas[datas["open"]>4]     # 2-4行,"date","open"列     ds = datas.loc[1:3,["date","open"]]     # 第2行     ds = datas.ix[[1]]     ds = datas[1:2]

列名

df.columns.values 返回 array 

或list(df.columns)     三、赋值     新增列     df['one_sort'] = sort_list     df['one_sort'] = 0     按条件赋值     df.one[df.two>0] = 0    

nan值处理

# 删除包含NaN值得任何行

df.dropna(axis = 0)

#将所有 NaN 值替换为 0

df.fillna(0)

 

删除列

```python
df_base.drop(['组件负责人_y','部门_y'],axis=1,inplace=True)```


删除行

.drop()方法若不设置参数inplace=True  df_base.drop([0],inplace=True)   

```python
# 筛选在的
df123=df123[df123.License_x.isin(['Apache','BSD','MIT','EPL'])]
# 筛选不在的
Version_list=list(df123.Version)
Version_list.remove('9999.0')
df123 = df123[df123.Version.isin(Version_list)]```


 删除重复的

```python
df_p=df_p.drop_duplicates(['姓名'],keep=False)```


删除含缺失值的行

```python
df1=df1.dropna(axis = 0,subset =['Version'])```


删除含缺失值的列

df1=df1.dropna(axis = 1,subset =[1])

 

四、转换         #第1行转为list

    params=datas.loc[1].tolist()

字典转dataframe

```python
df=pd.DataFrame.from_dict(dict)```


交集

```python
df12=pd.merge(df1,df2,on=['Component'],how='inner')```


并集

```python
df12=pd.merge(df1,df2,on=['Component'],how='outer')```


```python
差集(从df1中过滤df1在df2中存在的行):```


```python
df1 = df1.append(df2)
df1 = df1.append(df2)
df1 = df1.drop_duplicates(subset=['Component', 'Version'],keep=False)```


移动

# axis指定移动的轴:0为行,1为列

# period:参数指定移动的步幅,可以为正为负

# 整体下移1行

df.shift(axis=0, periods=1)

# 某列下移为新列 ,下移部分为nan

```python
df['open_new']=df['open'].shift(axis=0, periods=1)```


 

五、排序    # 按某列排序     df=df.sort_values(by='one',ascending=True)          # 对行进行排序并获取列ID     # Determine the max value and column name and add as columns to df     df['Max1'] = df.max(axis=1)     df['Col_Max1'] = df.idxmax(axis=1) 六、应用         将排名赋给列      # 按某列排序     df=df.sort_values(by='one',ascending=True)     sort_list=[]     df_len =df.iloc[:,0].size     for i  in range(1,df_len+1):         sort_list.append(i/df_len)     print(sort_list)     df['one_sort'] = sort_list     左连接

```python
result = pd.merge(left, right, how='left', on=['key1', 'key2'])

七、打印

显示所有列

pd.set_option('display.max_columns', None)

显示所有行

pd.set_option('display.max_rows', None)

八,导出csv

当有中文时,需要utf-8-sig,才能用excel打开,因为excel能够正确识别用gb2312、gbk、gb18030或utf_8 with BOM 编码的中文,如果是utf_8 no BOM编码的中文文件,excel打开会乱码

csv = df.to_csv(index=False,encoding="utf-8")
return CsvResponse(
    csv,
    status=200,
    headers=generate_download_headers("csv"),
    mimetype="application/csv",
)```



![](https://mutouzuo.oss-cn-hangzhou.aliyuncs.com/my/mudouzuo1.png)

标签:并集,df,list,df1,dataframe,python,pd,List,datas
From: https://www.cnblogs.com/bigleft/p/18179013

相关文章

  • FREERTOS:vTaskList函数
    函数原型:voidvTaskList(char*pcWriteBuffer);参数:pcWriteBuffer  一个缓冲区,上面提到的细节将以ASCII形式写入其中。假设此缓冲区的大小足以容纳产生的报告。大约为每个任务分配40字节的缓冲区就足够了。打印信息:任务任务状态优先级剩余......
  • [LeetCode] 2487. Remove Nodes From Linked List
    Youaregiventheheadofalinkedlist.Removeeverynodewhichhasanodewithagreatervalueanywheretotherightsideofit.Returntheheadofthemodifiedlinkedlist.Example1:Input:head=[5,2,13,3,8]Output:[13,8]Explanation:Thenodesth......
  • 开源电子邮件营销平台 listmonk 使用教程
    做产品肯定要做电子邮件营销,特别是面向海外的产品,电子邮件营销已成为企业与客户沟通、建立品牌忠诚度和推动销售的重要工具,可以直接接触到目标受众,提供个性化内容,并以相对较低的成本获得可观的投资回报。你看,MEAP又来提醒我买电子书了!做电子邮件营销首先需要考虑的是选哪个电子......
  • Phone List
    题目描述输入格式输出格式样例样例输入2391197625999911254265113123401234401234598346样例输出NOYES数据范围与提示这道题的三条判断是否存在前缀的标准:当在建树字符串已经到结尾时,如果该点有结束标记,那肯定是前缀(不是真前缀)当在建树字符串已经到......
  • grid 与 treelist 的区别
    TreeList与Grid的主要区别体现在数据结构、展示方式和应用场景上。以下是具体的分析:数据结构:TreeList:TreeList是一种树状的数据结构,它可以理解为是一个有序、可重复的树状列表。这种数据结构不仅实现了List接口,还融入了树的特性,如父子节点的关系,这使得它在处理具有层级关系的......
  • devexpress中 cxTreeList 与 cxVirtualTreeList 区别
    在DevExpress控件库中,cxTreeList和cxVirtualTreeList都是用于展示层级数据的控件,但它们在使用场景、性能优化和数据加载方式等方面有所不同。以下是两者之间的主要区别:数据展示与交互:cxTreeList:提供了一个传统的树形列表视图,用户可以直观地看到数据的层级结构,并通过展开和折......
  • List的remove()方法详解
    https://blog.csdn.net/anxin_hw/article/details/128312846一、错误使用场景1、普通for循环遍历List删除指定元素,list.remove(index)示例:将姓张的名字移除掉List<String>nameList=newArrayList<>(Arrays.asList("张三","李四","王五","赵六"));na......
  • CMakeLists.txt --- install使用
    例:cmake_minimum_required(VERSION3.9)project(test)set(CMAKE_BUILD_TYPEDebug)add_library(hahatest.cpp)install(TARGEThahaDESTINATION/home/linxisuo/project/test)install(DIRECTORY${CMAKE_SOURCE_DIR}/testDESTINATION/home/linxisuo)说明:1.安装......
  • CMakeListx.txt --- include_directories和target_include_directories命令
    1. include_directories语法include_directories([AFTER|BEFORE][SYSTEM]dir1[dir2...])作用将指定目录添加到编译器的头文件搜索路径之下,指定的目录被解释成当前源码路径的相对路径。参数默认情况下,include_directories命令会将目录添加到列表最后,可以通过命令设置......
  • CMakeLists.txt --- 导入接口库(预编译库)
    以接口库的方式导入预编译库cmake_minimum_required(VERSION3.9)project(test)set(CMAKE_BUILD_TYPEDebug)set(CMAKE_C_FLAGS"$ENV{CFLAGS}-O2-Wall-pthread")set(CMAKE_CXX_FLAGS"$ENV{CFLAGS}-O2-Wall-pthread-std=c++11-std=gnu++11")#设置mo......