我有一个这样的数据帧。我想知道如何将map函数应用于它的索引,并将其重命名为更简单的格式。
df = pd.DataFrame({'d': [1, 2, 3, 4]}, index=['apple_017', 'orange_054', 'orange_061', 'orange_053'])
df
d
apple_017 1
orange_054 2
orange_061 3
orange_053 4
数据帧的索引中只有两个标签,所以在这种情况下要么是苹果标签,要么是橙色标签,我就是这样尝试的:
data.index = data.index.map(i = "apple" if "apple" in i else "orange")
(显然不是这样的(
期望输出:
d
apple 1
orange 2
orange 3
orange 4
感谢任何人的帮助和建议!
通过split()
:尝试
df.index=df.index.str.split('_').str[0]
或
通过map()
:
df.index=df.index.map(lambda x:'apple' if 'apple' in x else 'orange')
df:的输出
d
apple 1
orange 2
orange 3
orange 4