如何将标题行添加到 Pandas DataFrame
我们将介绍在 pandas 的 dataframe 中添加标题行的方法,以及直接在 dataframe 中传递 names 或通过将列表中的列名直接分配给 dataframe.columns
方法的选项。
我们还将介绍 Pandas 的 DataFrame
添加标头,而不替换当前标头。换句话说,我们将当前标头向下移动,并将其添加到 DataFrame
中作为另一条记录。
我们还将看一下在读取 csv 文件时如何向 pandas.dataframe
添加标题行的例子。
通过直接在 dataframe 方法中传递标题行来添加标题行
我们将使用 columns
参数将 header
直接传递给 DataFrame
。
考虑以下代码:
# python 3.x
import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randint(0, 10, (6, 4)), columns=["a", "b", "c", "d"])
print(df)
输出:
a b c d
0 4 4 4 0
1 8 1 2 5
2 3 0 4 3
3 3 7 2 4
4 8 3 1 8
5 6 7 5 9
使用 dataframe.columns
添加标题行
我们还可以使用 dataframe.columns
将标题行添加到 DataFrame
中。
考虑以下代码:
# python 3.x
import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randint(0, 10, (6, 4)))
df.columns = ["a", "b", "c", "d"]
print(df)
输出:
a b c d
0 5 2 6 7
1 4 5 9 0
2 8 3 0 4
3 6 3 1 1
4 9 3 4 8
5 7 5 0 6
添加标头而不替换当前标头
另一种选择是将标题行添加为列索引的附加级别,以使其成为 MultiIndex
。当我们需要为列增加一层信息时,此方法很有用。
考虑以下代码:
# python 3.x
import pandas as pd
import numpy as np
df = pd.DataFrame(data=np.random.randint(0, 10, (6, 4)), columns=["a", "b", "c", "d"])
df.columns = pd.MultiIndex.from_tuples(zip(["A", "B", "C", "D"], df.columns))
print(df)
输出:
A B C D
a b c d
0 2 6 4 6
1 5 0 5 1
2 9 6 6 1
3 8 9 7 4
4 6 5 6 6
5 3 9 1 5
读取 csv 文件时,将 header
行添加到 DataFrame
中
我们可以直接在 read_csv
中使用 names
,或者如果文件没有标题,可以显式设置 header = None
。
考虑以下代码:
# python 3.x
import pandas as pd
import numpy as np
df = pd.Cov = pd.read_csv("path/to/file.csv", sep="\t", names=["a", "b", "c", "d"])
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串