Pandas数据处理实例笔记(持续更新)

版权声明:本文为连鹏伟原创文章,未经博主允许不得转载。 https://blog.csdn.net/lpwmm/article/details/80861306

对单个xlsx文件中全部工作簿进行合并

在一个xlsx文件中存在多个worksheet,其中的数据格式一致,将所有worksheet进行拼接合并,并导出csv

方法一:使用read_excel
import pandas as pd
df = pd.read_excel('xxx.xlsx', sheet_name=None, ignore_index=True)    #这里注意要带上后面的两个参数,否则会只加载第一个工作簿的数据
cdf = pd.concat(df.values())
cdf.to_csv('new.csv')
方法二:使用ExcelFile.pares
import pandas as pd

file = pd.ExcelFile('0629.xls')
print(file.sheet_names)
df = []
for sheet in file.sheet_names:
    df.append(file.parse(sheet))

cdf = pd.concat(df)
cdf.to_csv('concat.csv')
print('Job Done')

将DataFrame导出文件

df.to_excel('aaa.xlsx')    # 需要xlwt包的支持,用之前pip install xlwt一下,导出xlsx格式速度会比较慢,数据量大的时候不推荐
df.to_csv('bbb.csv', index=False, encoding='gb2312')    # index=False指定导出的文件中不带数据行号列,encoding指定文件编码,win下面必须指定gb2312,否则excel打开中文乱码

对DataFrame中的数据进行分类,然后获取每一分类的前n条

grouped = df.groupby(['class']).head(2)

使用列名对DataFrame进行数据选取

df[col]  #根据列名,并以Series的形式返回列
df[[col1, col2]]  #以DataFrame形式返回多列

使用iloc对DataFrame进行数据选取

# Single selections using iloc and DataFrame
# Rows:
data.iloc[0] # first row of data frame (Aleshia Tomkiewicz) - Note a Series data type output.
data.iloc[1] # second row of data frame (Evan Zigomalas)
data.iloc[-1] # last row of data frame (Mi Richan)
# Columns:
data.iloc[:,0] # first column of data frame (first_name)
data.iloc[:,1] # second column of data frame (last_name)
data.iloc[:,-1] # last column of data frame (id)

根据条件进行数据筛选

df[df[col] > 0.5]  # 选择col列的值大于0.5的行
df[df.iloc[:,15]=='xxx']  # 选择第15列(列标从0开始)等于xxx的行

查看DataFrame对象数据总行数

len(df)

Series类型对象合并两列数据

Series A和B进行合并计算

s1.combine_first(s2)

DataFrame相减处理(集合处理,不是数据减法计算)

How to remove a pandas dataframe from another dataframe, just like the set subtraction:

a=[1,2,3,4,5]
b=[1,5]
a-b=[2,3,4]

And now we have two pandas dataframe, how to remove df2 from df1:

In [5]: df1=pd.DataFrame([[1,2],[3,4],[5,6]],columns=['a','b'])
In [6]: df1
Out[6]:
   a  b
0  1  2
1  3  4
2  5  6


In [9]: df2=pd.DataFrame([[1,2],[5,6]],columns=['a','b'])
In [10]: df2
Out[10]:
   a  b
0  1  2
1  5  6

Then we expect df1-df2 result will be:

In [14]: df
Out[14]:
   a  b
0  3  4

Use pd.concat followed by drop_duplicates(keep=False)

pd.concat([df1, df2, df2]).drop_duplicates(keep=False)

It looks like

   a  b
1  3  4

续接两个Series对象

s1 = pd.Series([1,2,3])
s2 = pd.Series([2,5,6,7,8])
s = s1.append(s2)
# s:[1,2,3,2,5,6,7,8]

统计查看DataFrame/Series重复数据

例如上面的拼接后的s对象,其中的数值2是存在重复的,那么要查看的话这样操作:

>>> s
0    1
1    2
2    3
0    2
1    5
2    6
3    7
4    8
dtype: int64
>>> s.duplicated()    # 查看重复情况,不过这个结果看起来很不友好的,主要是用于获得重复数据的bool结果
0    False
1    False
2    False
0     True
1    False
2    False
3    False
4    False
dtype: bool
>>> s[s.duplicated()]    # 查看重复的具体数据
0    2
dtype: int64
>>> s[s.duplicated()].count()    # 统计重复数据数量
1

Series转DataFrame类型

Series对象就是一个一维数组而已,是没有列名属性的,转换成DataFrame对象加上列名

s.to_frame('列名')

根据指定列对两个DataFrame进行相减处理去除重复行

有两个DataFrame对象df1是完整数据,df2是一个Series转换过来的DataFrame对象,其实就一列,现在想从df1中找出所有电话列=df2中数据的行删除掉,得到期望结果


result = pd.concat([df1,df2], ignore_index=True, sort=False).drop_duplicates(subset='电话', keep=False)



猜你喜欢

转载自blog.csdn.net/lpwmm/article/details/80861306