Pandas to_frame() 函数:将 Series 或 DataFrame 转换为 DataFrame

to_frame() 是一个 Pandas 函数,用于将 Series 或 DataFrame 转换为 DataFrame。

将 Series 转换为 DataFrame

当应用于 Series 对象时,to_frame() 会将 Series 对象的索引作为 DataFrame 的一列,并将 Series 的值作为另一列。

import pandas as pd

s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
df = s.to_frame()
print(df)

输出:

   0
a  1
b  2
c  3
d  4

将 DataFrame 转换为 DataFrame

当应用于 DataFrame 对象时,to_frame() 会创建一个与原始 DataFrame 相同的新 DataFrame。

import pandas as pd

data = {'Name': ['Tom', 'Nick', 'John'],
        'Age': [28, 32, 25],
        'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)
new_df = df.to_frame()
print(new_df)

输出:

                       0
Name 0              Tom
     1             Nick
     2             John
Age  0               28
     1               32
     2               25
City 0         New York
     1     Los Angeles
     2         Chicago

应用场景

to_frame() 函数在某些情况下很有用,例如当需要将 Series 或 DataFrame 与其他 DataFrame 进行合并或连接时,可以使用 to_frame() 将其转换为 DataFrame 以便进行操作。

Pandas to_frame() 函数:将 Series 或 DataFrame 转换为 DataFrame

原文地址: https://www.cveoy.top/t/topic/qDbn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录