【发布时间】:2020-10-06 02:43:30
【问题描述】:
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)
print(randn(5, 4))
df = pd.DataFrame( randn(5, 4), ['A', 'B', 'C', 'D', 'F'], ['W', 'X', 'Y', 'Z'] )
tmp_df = df['X']
print(type(tmp_df)) # Here type is Series (as expected)
tmp_df.loc[:] = 12.3
print(tmp_df)
print(df)
此代码更改(原始)DataFrame df 的内容。
np.random.seed(101)
print(randn(5, 4))
df = pd.DataFrame( randn(5, 4), ['A', 'B', 'C', 'D', 'F'], ['W', 'X', 'Y', 'Z'] )
tmp_df = df.loc[['A', 'B'], ['W', 'X']]
print(type(tmp_df)) # Type is DataFrame
tmp_df.loc[:] = 12.3 # whereas, here when I change the content of the tmp_df it doesn't reflect on original array.
print(tmp_df)
print(df)
那么,这是否意味着如果我们从 DataFrame 中将 Series 切片,引用将传递给切片对象。 然而,如果它是被切片的 DataFrame,那么它不会指向原始 DataFrame。
请确认我上面的结论是否正确?我们将不胜感激。
【问题讨论】:
-
您确定
tmp_df = df[['A', 'B'], ['W', 'X']]部分适合您吗? -
@LazyCoder,更新了错字。谢谢
标签: python-3.x pandas numpy dataframe numpy-slicing