如何 add/delete 多索引数据帧中的索引 Python
How to add/delete an index in a multi index dataframe Python
我有一个多索引数据框,我想在其中添加一个具有 6 个值的 "three" 索引,其中 2 个用于 X 和 Y 列中的 a、b 和 c。
import pandas as pd, numpy as np
np.arrays = [["one", "one", "one", "two", "two", "two"], ["a", "b", "c", "a", "b", "c"]]
df = pd.DataFrame(np.random.randn(6,2),
index = pd.MultiIndex.from_tuples(list(zip(*np.arrays))),
columns = ["X", "Y"])
df = round(abs(df), 3)
df
X Y
one a 1.521 0.048
b 1.595 1.783
c 0.286 1.042
two a 1.480 1.071
b 0.807 1.058
c 1.730 1.233
我想要的是:
X Y
one a 1.521 0.048
b 1.595 1.783
c 0.286 1.042
two a 1.480 1.071
b 0.807 1.058
c 1.730 1.233
three a 1.2 5.5
b 4.2 2.2
c 7.8 3.4
另外,如何删除索引?我尝试了以下代码,但它给出了一个 AttributeError:delitem
del df.loc["one"]
任何帮助都会很棒。
一种使用 pd.concat 的方法,即
idx = pd.MultiIndex.from_tuples(list(zip(['three']*3,list('abc'))))
new = pd.DataFrame(np.random.randn(3,2), index=idx, columns= df.columns)
new_df = pd.concat([df,new])
X Y
one a 0.270000 0.299000
b 0.644000 0.073000
c 1.224000 0.656000
two a 0.202000 0.097000
b 2.750000 0.373000
c 0.421000 0.939000
three a 1.392999 -0.870480
b -1.899386 -0.249068
c -0.609149 0.164459
删除使用 drop 即
new_df = new_df.drop('one',level=0)
我有一个多索引数据框,我想在其中添加一个具有 6 个值的 "three" 索引,其中 2 个用于 X 和 Y 列中的 a、b 和 c。
import pandas as pd, numpy as np
np.arrays = [["one", "one", "one", "two", "two", "two"], ["a", "b", "c", "a", "b", "c"]]
df = pd.DataFrame(np.random.randn(6,2),
index = pd.MultiIndex.from_tuples(list(zip(*np.arrays))),
columns = ["X", "Y"])
df = round(abs(df), 3)
df
X Y
one a 1.521 0.048
b 1.595 1.783
c 0.286 1.042
two a 1.480 1.071
b 0.807 1.058
c 1.730 1.233
我想要的是:
X Y
one a 1.521 0.048
b 1.595 1.783
c 0.286 1.042
two a 1.480 1.071
b 0.807 1.058
c 1.730 1.233
three a 1.2 5.5
b 4.2 2.2
c 7.8 3.4
另外,如何删除索引?我尝试了以下代码,但它给出了一个 AttributeError:delitem
del df.loc["one"]
任何帮助都会很棒。
一种使用 pd.concat 的方法,即
idx = pd.MultiIndex.from_tuples(list(zip(['three']*3,list('abc'))))
new = pd.DataFrame(np.random.randn(3,2), index=idx, columns= df.columns)
new_df = pd.concat([df,new])
X Y
one a 0.270000 0.299000
b 0.644000 0.073000
c 1.224000 0.656000
two a 0.202000 0.097000
b 2.750000 0.373000
c 0.421000 0.939000
three a 1.392999 -0.870480
b -1.899386 -0.249068
c -0.609149 0.164459
删除使用 drop 即
new_df = new_df.drop('one',level=0)