简体   繁体   中英

Multiple column names in Pandas DataFrame

I am currently moving some data from a numpy array to a Pandas DataFrame so that I can refer to columns by their name, rather than their index. The problem that I have is that I would like to allow for multiple names to refer to the same column.

data = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
df = pd.DataFrame(data, columns=('Sensor1231', 'Sensor4221', 'Sensor4673'))

Sensor4221, for example, is an accelerometer on the 5th level of a structure. I want to add an additional label so (eg. AccLevel5) so that I can refer to the column without having to remember an obscure sensor number.

Therefore, both of the following will provide the same output.

Accel = df['Sensor4221']

and

Accel = df['AccLevel5']

both give:

2
5
8

the dataframe is a wrapper on the numpy array. You can assign another dataframe pointing to the same array to accomplish your goal.

data = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
df = pd.DataFrame(data, columns=('Sensor1231', 'Sensor4221', 'Sensor4673'))

df2 = pd.DataFrame(df.values, df.index,
                   columns=('Sensor1231', 'AccLevel5', 'Sensor4673'))

df

在此处输入图片说明

df2

在此处输入图片说明


now reasign an element in df and see the change in df2

df.loc[1, 'Sensor4221'] = 999

df2

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM