Pandas的这两种用法之间是否存在有意义的差异?



我正在使用pandas,我想出了两种不同的方法来做某事:

import pandas as pd
def csv_parser(path):
a = pd.read_csv(path)

return a
teeburu = csv_parser(R"H:DocumentsCodingProjectTables1 - Overall Type Table.csv")
print(type(teeburu.iloc[0,1]))
print(type(teeburu.iloc[0,0]))

:

import pandas as pd
def csv_parser(path):
a = pd.read_csv(path)

return a
teeburu = csv_parser(R"H:DocumentsCodingProjectTables1 - Overall Type Table.csv")
teeburu_df = pd.DataFrame(data=teeburu)
print(type(teeburu_df.iloc[0,1]))
print(type(teeburu_df.iloc[0,0]))

我想知道的是两者之间是否有任何有意义的区别,如果我不使用pd.DataFrame函数,它仍然会在内部存储表。

是的,你应该使用第一个。

第二个创建一个新的数据框架对象,位于不同的内存地址(您可以使用id函数检查这一点),但具有相同的底层数据。

这意味着如果你用inplace改变了第一个数据帧中的一些数据(你不应该使用但无论如何),它也会在第二个数据帧中改变。

例子
import pandas as pd
def csv_parser(path):
a = pd.read_csv(path)
return a
teeburu_df1 = csv_parser('data.csv')
teeburu_df2 = pd.DataFrame(data=teeburu_df1)
print('Before')
print(teeburu_df2)
teeburu_df1.fillna(1, inplace=True)
print('nAfter')
# After changing first dataframe with inplace, second one changes
print(teeburu_df2)

print('nId of first df', id(teeburu_df1))  # Prints different id than below
print('Id of second df', id(teeburu_df2))  # Prints different id than above

打印

Before
A   B
0   NaN NaN
1  19.0 NaN
After
A    B
0   1.0  1.0
1  19.0  1.0
Id of first df 139865179561408
Id of second df 139866333609936
csv:

A,B
,
19,

最新更新