• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Pandas轻松学会21个入门操作技巧!

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

介绍

Pandas是易于使用且功能强大的数据分析库。像NumPy一样,它向量化了大多数基本操作,使其能在CPU上可以并行计算,从而加快了计算速度。此处指定的操作非常基础,但是如果您刚开始使用Pandas,则太重要了。在这里,我们来看如何将 Pandas 导入为“ pd”,然后使用“ pd”对象执行其他基本的 Pandas 操作。

1.如何从CSV文件或文本文件读取数据?

CSV文件是comma-separated(“,”分割的),因此要读取CSV文件,请执行以下操作:

df = pd.read_csv(file_path, sep=’,’, header = 0, index_col=False,names=None)
Explanation:‘read_csv’ function has a plethora of parameters and I have specified only a few, ones that you may use most often. A few key points:
a) header=0 means you have the names of columns in the first row in the file and if you don’t you will have to specify header=None
b) index_col = False means to not use the first column of the data as an index in the data frame, you might want to set it to true if the first column is really an index.
c) names = None implies you are not specifying the column names and want it to be inferred from csv file, which means that your header = some_number contains column names. Otherwise, you can specify the names in here in the same order as you have the data in the csv file. 

If you are reading a text file separated by space or tab, you could simply change the sep to be:sep = " " or sep='\t'

2.如何使用预先存在的列或NumPy 2D数组创建数据框(DataFrame)?

使用字典

# c1, c2, c3, c4 are column names. 
d_dic ={'first_col_name':c1,'second_col_names':c2,'3rd_col_name':c3} 
df = pd.DataFrame(data = d_dic)

使用NumPy数组

np_data = np.zeros((no_of_samples,no_of_features)) #any_numpy_array
df = pd.DataFrame(data=np_data, columns = list_of_Col_names)

3.如何可视化数据框(DataFrame)中的顶部和底部x值?

df.head(num_of_rows_to_view) #top_values
df.tail(num_of_rows_to_view) #bottom_values
col = list_of_columns_to_view 
df[col].head(num_of_rows_to_view)
df[col].tail(num_of_rows_to_view)

4.如何重命名一个或多个列?

df = pd.DataFrame(data={'a':[1,2,3,4,5],'b':[0,1,5,10,15]})
new_df = df.rename({'a':'new_a','b':'new_b'})

将返回数据帧存储到新数据帧中很重要,因为重命名不是原地操作的(in-place)。

5.如何获取列表中的列名?

df.columns.tolist()

如果只想遍历名称,但不使用 tolist()函数也可以完成此工作,但它会将所有内容作为索引对象返回。

6.如何获得一系列数值的频率?

df[col].value_counts() #returns a mapper of key,frequency pair
df[col].value_counts()[key] to get frequency of a key value

7.如何将索引重置为现有列或其他列表或数组?

new_df = df.reset_index(drop=True,inplace=False)

如果你这样做inplace = True,则无需将其存储到new_df中。另外,当您将索引重置为pandas RangeIndex()时,您可以选择保留旧索引或使用“ drop”参数将其删除。

8.如何删除列?

df.drop(columns = list_of_cols_to_drop)

9.如何更改DataFrame(数据帧)中的索引?

df.set_index(col_name,inplace=True)

这会将col_name col设置为索引。您可以传递多个列以将它们设置为索引。 inplace关键字的作用与之前所述相同。

10.如果行或列具有nan值,如何删除?

df.dropna(axis=0,inplace=True)

axis = 0将删除任何您可能不希望使用nan值的列。 axis = 1将仅删除任何列中具有nan值的行。

11.如何在给定条件的情况下切片数据帧(DataFrame)?

您始终需要以逻辑条件的形式指定掩码。
例如,如果您具有列年龄,并且您想选择其中年龄列具有特定值或位于列表中的数据框(DataFrame)。那么,您可以实现切片,如下所示:

mask = df['age'] == age_value 
or
mask = df['age].isin(list_of_age_values)
result = df[mask]

有多个条件:例如选择高度和年龄都与特定值对应的行。

mask = (df['age']==age_value) & (df['height'] == height_value)
result = df[mask]

12.如何在给定列名或行索引值的情况下切片数据帧(DataFrame)?

这里有4个选项:at,iat,loc和iloc。“ iat”和“ iloc”,它们相似之处在于它们提供基于整数的索引,而“ loc”和“ at”则提供基于名称的索引。

这里要注意的另一件事是,在使用“ loc”和“ iloc”对单个元素进行“提供”索引时,“ iat”可以切片多个元素。

Examples:
a) 
df.iat[1,2] provides the element at 1th row and 2nd column. Here it's important to note that number 1 doesn't correspond to 1 in index column of dataframe. It's totally possible that index in df does not have 1 at all. It's like python array indexing.
b)
df.at[first,col_name] provides the value in the row where index value is first and column name is col_name
c)
df.loc[list_of_indices,list_of_cols] 
eg df.loc[[4,5],['age','height']]
Slices dataframe for matching indices and column names
d)
df.iloc[[0,1],[5,6]] used for interger based indexing will return 0 and 1st row for 5th and 6th column.

13.如何遍历行?

iterrows() and itertuples()
for i,row in df.iterrows():
    sum+=row['hieght']
iterrows() passess an iterators over rows which are returned as series. If a change is made to any of the data element of a row, it may reflect upon the dataframe as it does not return a copy of rows.
itertuples() returns named tuples
for row in df.itertuples():
    print(row.age)

14.如何按列排序?

df.sort_values(by = list_of_cols,ascending=True) 

15.如何将函数应用于序列中的每个元素?

df['series_name'].apply(f) 
where f is the function you want to apply to each element of the series. If you also want to pass arguments to the custom function, you could modify it like this.
def f(x,**kwargs):
    #do_somthing
    return value_to_store
df['series_name'].apply(f, a= 1, b=2,c =3)
If you want to apply a function to more than a series, then:
def f(row):
    age = row['age']
    height = row['height']
df[['age','height']].apply(f,axis=1)
If you don't use axis=1, f will be applied to each element of both the series. axis=1 helps to pass age and height of each row for any manipulation you want.

16.如何将函数或者方法应用于数据框中的所有元素?

new_df = df.applymap(f)

17.如果一系列值位于列表中,如何切片数据帧?

使用masking和isin。要选择年龄在列表中的数据样本:

df[df['age'].isin(age_list)]

要选择相反的数据,则使用年龄不在列表中的数据样本:

df[~df['age'].isin(age_list)]

18.如何对列值进行group-by并且在另一列上汇总或应用函数?

df.groupby(['age']).agg({'height':'mean'})

这将按“年龄”系列对数据框(DataFrame)进行分组,而高度列将应用分组值的平均值。有时,您想要group-by某个列并将其他列的所有相应的分组元素转换为列表。您可以通过以下方法实现此目的:

df.groupby(['age']).agg(list)

19.如何为特定列列表中的每个元素的其他列创建重复项?

这个问题可能有点令人困惑。我的实际意思是,假设您具有以下数据帧df:

Age Height(in cm)
>20  180
20  175
18  165
18  163
16  170

将group-by与列表聚合器一起使用后,您可能会得到类似以下内容的信息:

Age Height(in cm)
20  [180,175]
18  [165,163]
16  [170]

现在,如果您要通过撤消上一个操作返回到原始数据帧,该怎么办?您可以使用0.25版 Pandas 中新引入的名为explode的操作来实现这一点。

df['height'].explode() will give the desired outcome.

20.如何连接两个DataFrame(数据帧)?

假设您有两个data-frames df1和df2,它们具有给定的列名称,年龄和身高,并且您希望实现两列的串联。 axis = 0是垂直轴。在这里,结果data-frame将具有从data-frames追加的列:

df1 --> name,age,height
df2---> name,age,height
result = pd.concat([df1,df2],axis=0)

对于水平串联,

df1--> name,age
df2--->height,salary
result = pd.concat([df1,df2], axis=1) 

21.如何合并两个数据帧?

For the previous example, assume you have an employee database forming two dataframes like
df1--> name, age, height
df2---> name, salary, pincode, sick_leaves_taken
You may want to combine these two dataframe such that each row has all details of an employee. In order to acheive this, you would have to perform a merge operation.
df1.merge(df2, on=['name'],how='inner')
This operation will provide a dataframe where each row will comprise of name, age, height, salary, pincode, sick_leaves_taken. 
how = 'inner' means include the row in result if there is a matching name in both the data frames. For more read: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html?highlight=merge#pandas.DataFrame.merge

总结

对于任何初学者的数据分析项目,您可能需要非常了解这些操作。我一直发现Pandas是一个非常有用的库,现在您可以与其他各种数据分析工具和语言集成。在学习支持分布式算法的语言时,了解 Pandas 操作甚至可能会有所帮助。


鲜花

握手

雷人

路过

鸡蛋
专题导读
上一篇:
Python的Jupyter Notebook入门教程发布时间:2022-05-14
下一篇:
python - Keras,如何获得每一层的输出?代码实例发布时间:2022-05-14
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap