我正在创建一个数据框来存储样本信息。我的一些列标签的格式为索引:子索引。有更好的方法吗?我正在查看 pd.MultiIndex 但我的子索引特定于该索引。
import pandas as pd
df = pd.DataFrame(
np.random.random(size=(1234, 6)),
columns=['ID',
'Charge:pH2', 'Charge:pH4', 'Charge:pH6',
'Extinction:Wavelength200nm', 'Extinction:Wavelength500nm'])
我希望能够调用 df.loc[:, 'ID']
或 df.loc[:, 'Charge']
或 df.loc[:, ('电荷', 'pH6')]
最佳答案
您可以使用MultiIndex.from_tuple :
import numpy as np
import pandas as pd
df = pd.DataFrame(
np.random.random(size=(1234, 6)),
columns=['ID','Charge:pH2', 'Charge:pH4', 'Charge:pH6','Extinction:Wavelength200nm', 'Extinction:Wavelength500nm'])
df.columns = pd.MultiIndex.from_tuples(map(tuple, df.columns.str.split(':')))
print(df.head(10))
输出
ID Charge ... Extinction
NaN pH2 ... Wavelength200nm Wavelength500nm
0 0.301592 0.137384 ... 0.074137 0.339948
1 0.737711 0.557524 ... 0.813727 0.586845
2 0.615398 0.529687 ... 0.148700 0.466916
3 0.411509 0.725513 ... 0.380019 0.876992
4 0.031172 0.623944 ... 0.311610 0.488207
5 0.022140 0.450630 ... 0.422927 0.479094
6 0.119681 0.221624 ... 0.710848 0.719201
7 0.252039 0.632321 ... 0.453235 0.952687
8 0.379501 0.356493 ... 0.141977 0.028836
9 0.249950 0.316020 ... 0.307337 0.881437
[10 rows x 6 columns]
所有必需的索引方案都有效:
print(df.loc[:, 'ID'].shape)
print(df.loc[:, 'Charge'].shape)
print(df.loc[:, ('Charge', 'pH6')].shape)
输出
(1234, 1)
(1234, 3)
(1234,)
关于python - 如何在 DataFrame 的一列中添加 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54651505/