[英]How can I combine the Index in the python dataframe?
in the following, can I make a single index for all the entries with common index.在下面,我可以为所有具有公共索引的条目创建一个索引吗?
cric = pd.Series(['India', 'Pakistan', 'South Africa', 'England', 'New Zealand'],
index = ['Cricket', 'Cricket', 'Cricket', 'Cricket', 'Cricket'])
ftbl = pd.Series(['England', 'South Africa', 'Australia', 'Netherlands', 'New Zealand'],
index = ['Football', 'Football', 'Football', 'Football' , 'Football'])
hock = pd.Series(['India', 'Pakistan', 'South Korea', 'England', 'India', 'New Zealand'],
index = ['Hockey', 'Hockey', 'Hockey', 'Hockey', 'Hockey', 'Hockey'])
all_countries_1 = cric.append(ftbl)
all_countries_1 = all_countries_1.append(ftbl)
all_countries_1 = all_countries_1.append(hock)
all_countries_1 = all_countries_1.to_frame()
all_countries_1.columns = ['Countries']
all_countries_1
If, by single index, you mean an index made of autoincrementing numbers, there is nothing special you have to do.如果,通过单个索引,您的意思是由自动递增数字组成的索引,那么您无需做任何特别的事情。 That is the default index for a DataFrame, so using the
reset_index()
method will get what you want.这是 DataFrame 的默认索引,因此使用
reset_index()
方法将获得您想要的。 The next step will probably be to rename your index column.下一步可能是重命名索引列。 You can chain that method with
reset_index
and take care of it one line.您可以使用
reset_index
链接该方法并在一行中处理它。
all_countries_1 = all_countries_1.reset_index().rename(columns={"index":"Sports"})
Is this what you are looking for?这是你想要的?
# zip the first three chars of the index and the index together
z = list(zip(all_countries_1.index.str[:3], all_countries_1.index))
# create multi index
idx = pd.MultiIndex.from_tuples(z)
# assign index
all_countries_1.index = idx
Countries
Cri Cricket India
Cricket Pakistan
Cricket South Africa
Cricket England
Cricket New Zealand
Foo Football England
Football South Africa
Football Australia
Football Netherlands
Football New Zealand
Football England
Football South Africa
Football Australia
Football Netherlands
Football New Zealand
Hoc Hockey India
Hockey Pakistan
Hockey South Korea
Hockey England
Hockey India
Hockey New Zealand
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.