pandas 使用笔记

February 28, 2024

在 pandas 中创建空 DataFrame

# import pandas library as pd
import pandas as pd
 
# create an Empty DataFrame
# object With column names only
df = pd.DataFrame(columns = ['Name', 'Scores', 'Questions'])
print(df)
'''
OUTPUT:
Empty DataFrame
Columns: [Name, Scoress, Questions]
Index: []
'''
# append rows to an empty DataFrame
df = df.append({'Name' : 'Anna', 'Scores' : 97, 'Questions' : 2200}, 
                ignore_index = True)
df = df.append({'Name' : 'Linda', 'Scores' : 30, 'Questions' : 50},
                ignore_index = True)
df = df.append({'Name' : 'Tommy', 'Scores' : 17, 'Questions' : 220},
               ignore_index = True)
print(df)
'''
OUTPUT:
Name Scores	Questions
0	Anna	97	2200
1	Linda	30	50
2	Tommy	17	220
'''
# import pandas library as pd
import pandas as pd
 
# create an Empty DataFrame object With
# column names and indices 
df = pd.DataFrame(columns = ['Name', 'Scores', 'Questions'], 
                   index = ['a', 'b', 'c'])
 
print("Empty DataFrame With NaN values : \n\n", df)
'''
Empty DataFrame With NaN values : 
   Name    Scores Questions
a  NaN      NaN      NaN
b  NaN      NaN      NaN
c  NaN      NaN      NaN
'''
 
# adding rows to an empty 
# dataframe at existing index
df.loc['a'] = ['Anna', 50, 100]
df.loc['b'] = ['Pete', 60, 120]
df.loc['c'] = ['Tommy', 30, 60]
 
print(df)
'''
    Name	Scores  Questions
a	Anna	50	100
b	Pete	60	120
c	Tommy	30	60
'''

导出 pandas DataFrame 时移除表头

dataframe = pd.read_csv("test.csv",sep=",", header=None)

sep 是 CSV 的字段分隔符,默认是逗号。请按实际文件使用的分隔符设置它。

  1. pandas.DataFrame.to_csv. (n.d.). pandas docs. Retrieved Feb 28, 2024, from https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

将 DataFrame 划分为训练集和测试集

# Using DataFrame.sample() Method by random_state arg.
train=df.sample(frac=0.8,random_state=200)
test=df.drop(train.index)
print(train)

想得到可重复的划分,可以设置 random_state。同一个值控制随机划分,重复运行会得到相同结果。

怎样获取 DataFrame 的行数?

给定一个 DataFrame df,可以使用下面的写法:

len(df.index)
df.shape[0]

⚠️ 注意: df.count() 按列统计非 NA/NaN 值的个数。如果某列有缺失值,结果就不是总行数。

  1. root(2013 年 4 月 11 日回答),Mateen Ulhaq(2021 年 10 月 6 日编辑)。对于 df,可选用下列写法: len(df.index) df.shape[0] df[df.columns[0]].count()(统计第一列非 NaN 值的数量) 性能对比图 复现图表的代码: import numpy as np import pandas as pd import perfplot perfplot.save( "out.png", setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)), n_range=[2**k for k in range(25)], kernels=[ lambda df: len(df.index), lambda df: df.shape[0], lambda df: df[df.columns[0]].count(), ], labels=["len(df.index)", "df.shape[0]", "df[df.columns[0]].count()"], xlabel="Number of rows", ). [Answer]. stackoverflow. https://stackoverflow.com/a/15943975

用 pandas 对一列数据分箱

指定分箱标签

默认情况下,cut() 返回分类变量,标签与分箱边界对应。可以通过 labels 参数自定义标签:

bins = [0, 20, 40, 60, 80]
labels = ['young', 'middle-aged', 'old', 'very-old']

df['age_bin'] = pd.cut(df['age'], bins, labels=labels)

print(df)
Output:

   age      age_bin
0   18        young
1   25  middle-aged
2   30  middle-aged
3   35  middle-aged
4   40  middle-aged
5   45          old
6   50          old
7   55          old
8   60          old
9   65     very-old

这里用 labels 参数为每个箱指定了名称,分类值因此更容易理解。

按分位数分箱

除了手动指定边界,还可以用 qcut() 按分位数分箱。qcut() 接收连续变量和分位区间数,返回表示各区间的分类变量。

df['age_bin'] = pd.qcut(df['age'], q=4, labels=False)

print(df)
Output:

   age  age_bin
0   18        0
1   25        0
2   30        1
3   35        1
4   40        2
5   45        2
6   50        3
7   55        3
8   60        3
9   65        3

本例用 qcut() 将 age 列分成四个分位区间,结果用 0 到 3 表示所属区间。

  1. @Saturn Cloud. (June 19, 2023). Binning a Column with Python Pandas. saturncloud. [Blog post]. Retrieved February 28, 2024, from https://saturncloud.io/blog/binning-a-column-with-python-pandas/#specify-bin-labels

向 DataFrame 插入空值

import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'col1': [1, 2, None], 'col2': [3, None, 5]})

# check for null values
null_df = df.isnull()
print(null_df)
'''
Output:
    col1   col2
0  False  False
1  False   True
2   True  False
'''

输出的 CSV 如下(None 对应的位置留空):

col1,col2
1,3
2,
,5
  1. How to Check if a Particular Cell in Pandas DataFrame is Null. (June 19, 2023). [Blog post]. saturncloud. Retrieved from https://saturncloud.io/blog/how-to-check-if-a-particular-cell-in-pandas-dataframe-is-null/

将 DataFrame 追加到已有 CSV 文件

# if file does not exist write header 
if not os.path.isfile(output_filename):
    df.to_csv(output_filename, index=False, mode='a')
else: # else it exists so append without writing the header
    df.to_csv(output_filename, index=False, header=False, mode='a')

📓 说明: 追加时还要留意是否写出表头,否则每次写入都可能重复表头,例如:

dataset_name,algo_name,threshold
cars,no_resample,0.1
dataset_name,algo_name,threshold
cars,no_resample,0.1
  1. Padraic Cunningham(2015 年 6 月 22 日)答:可以先用 os.path.isfile('filename.csv') 检查文件。文件不存在时用 df.to_csv 写表头,已存在时用 mode='a'、header=False 追加数据而不重复写表头。Stack Overflow。https://stackoverflow.com/questions/30991541/pandas-write-csv-append-vs-write/30991707#30991707

将训练数据拆成 X 和 y

    # load whole dataset from csv
    df = pd.read_csv(CSV_FILENAME)

    # remove column 'y' from the dataframe
    # if df.drop(columns=[target_column], inplace=True), then df will be changed
    X = df.drop(columns=[target_column])

    # df[[colname1,colname2,...]] returns a copy slice of the original dataframe
    # df is untouched
    y = df[[target_column]]

将 X 和 y 拼回同一个 DataFrame

使用 df = pd.concat([X, y], axis=1)。

  1. Pandas DataFrame: How to concatenate with Python examples. (August 15, 2023). [Blog post]. Capital One Tech. Retrieved April 2, 2024, from https://www.capitalone.com/tech/open-source/pandas-dataframe-concat/

  2. Merge, join, concatenate and compare. (n.d.). pandas. Retrieved April 2, 2024, from https://pandas.pydata.org/docs/user_guide/merging.html#concatenating-series-and-dataframe-together

  3. How to add one row in an existing Pandas DataFrame?. (04 Jan, 2024). geeksforgeeks. Retrieved from https://www.geeksforgeeks.org/how-to-add-one-row-in-an-existing-pandas-dataframe/

怎样选取 DataFrame 的子集?

# I’m interested in the names of the passengers older than 35 years.
In [23]: adult_names = titanic.loc[titanic["Age"] > 35, "Name"]

In [24]: adult_names.head()
Out[24]: 
1     Cumings, Mrs. John Bradley (Florence Briggs Th...
6                               McCarthy, Mr. Timothy J
11                             Bonnell, Miss. Elizabeth
13                          Andersson, Mr. Anders Johan
15                     Hewlett, Mrs. (Mary D Kingcome) 
Name: Name, dtype: object


# I’m interested in rows 10 till 25 and columns 3 to 5.
In [25]: titanic.iloc[9:25, 2:5]
Out[25]: 
    Pclass                                 Name     Sex
9        2  Nasser, Mrs. Nicholas (Adele Achem)  female
10       3      Sandstrom, Miss. Marguerite Rut  female
11       1             Bonnell, Miss. Elizabeth  female
12       3       Saundercock, Mr. William Henry    male
13       3          Andersson, Mr. Anders Johan    male
..     ...                                  ...     ...
20       2                 Fynney, Mr. Joseph J    male
21       2                Beesley, Mr. Lawrence    male
22       3          McGowan, Miss. Anna "Annie"  female
23       1         Sloper, Mr. William Thompson    male
24       3        Palsson, Miss. Torborg Danira  female

[16 rows x 3 columns]

💡 提示: 这里要注意通过 loc/iloc 修改数据时是否会影响原 DataFrame;如果需要完全独立的一份,应显式复制。

  1. How do I select a subset of a DataFrame?. (n.d.). pandas. Retrieved April 2, 2024, from https://pandas.pydata.org/docs/getting_started/intro_tutorials/03_subset_data.html#how-do-i-select-a-subset-of-a-dataframe

  2. JohnE(2018 年 9 月 5 日)答:情形 A 要求修改 df2 不影响 df1。此时显式执行 df2 = df1.copy(),便能得到两份彼此独立的数据,之后修改其中任意一个都不会影响另一个。情形 B 的要求则是修改 df2 时也影响 df1。Stack Overflow。https://stackoverflow.com/questions/48173980/pandas-knowing-when-an-operation-affects-the-original-dataframe/52182208#52182208

如何修改 pandas DataFrame 一列中的所有值

第一步:选取列

可以用方括号把列名当作键,从 DataFrame 中选取一列。例如,df 有一列名为 age,可这样选取:

age_column = df['age']

第二步:对每个值应用函数

选好列后,用 .apply() 对每个值执行同一个函数。函数接收当前值这一个参数,返回要替换进去的新值。

比如,想把 age 列的所有值替换成平方根,可以定义下面的函数:

import numpy as np

def sqrt(x):
    return np.sqrt(x)

然后用 .apply() 将函数应用到 age 列的每个值上:

new_age_column = age_column.apply(sqrt)

得到的新 Series 名为 new_age_column,其中包含原值的平方根。

第三步:把新值赋回该列

仍然用方括号选中原列,并将新的 Series 赋给它,例如:

df['age'] = new_age_column

这样就会用新值替换原 DataFrame df 中的 age 列。

示例

RULESET = {
    ' United-States': 'us',
}
def chg_to_ruleset(v, ruleset):
    if v in ruleset:
        return ruleset[v]
    else:
        return 'others'

y = df[['native-country']]
df[['native-country']] = y.applymap(lambda x: chg_to_ruleset(x, ruleset=RULESET))

⚠️ 注意: DataFrame.applymap 从 2.1.0 版本起已弃用,请改用 DataFrame.map。

  1. How to Change All the Values of a Column in a Pandas DataFrame. (June 19, 2023). [Blog post]. saturncloud. Retrieved from https://saturncloud.io/blog/pandas-how-to-change-all-the-values-of-a-column/

  2. pandas.DataFrame.applymap. (n.d.). pandas. Retrieved April 2, 2024, from https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.applymap.html

延伸阅读

  1. @古明地盆. (18 Mar, 2020.). 详解pandas的read_csv方法. cnblogs. [Blog post]. Retrieved February 28, 2024, from https://www.cnblogs.com/traditional/p/12514914.html

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-02-28). pandas 使用笔记. https://caiborui.com/blog/2024-02-28-en-pandas-tips-zhtrans

@misc{borui2024-47d0a503,
  author = {borui},
  title = {{pandas 使用笔记}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-02-28-en-pandas-tips-zhtrans}
}