我是python和pandas库的新手。我有12000行和3列,例如:
A B C
Husband Test1 $1200
Kids Test1 $1288
Wife Test1 $1232
Cousin Test1 $3265
预期结果:
A B C
Husband Test1 $1200
Wife Test1 $1232
Kids Test1 $1288
Cousin Test1 $3265
A B C
Husband Test2 $1200
Kids Test2 $1288
Cousin Test2 $3265
Wife Test2 $1232
预期结果:
A B C
Husband Test2 $1200
Wife Test2 $1232
Kids Test2 $1288
Cousin Test2 $3265
所以我在哪里看到";妻子";,我希望整排都移到丈夫下面。我用了上面的两个例子。这就是我目前拥有的
import pandas as pd
df = pd.read_csv("Test.csv")
df1=pd.DataFrame()
df1 = df.append(df[df["Relationship"] == "Husband"])
df1 = df.append(df[df["Relationship"] == "Wife"])
df1 = df.append(df[df["Relationship"] == "Kids"])
df1 = df.append(df[df["Relationship"] == "Cousin"])
print(df1)
对列A
的指定自定义顺序使用有序类别,因此DataFrame.sort_values
获得指定顺序:
df = pd.read_csv("Test.csv")
df['A'] = pd.Categorical(df.A, ordered=True, categories=['Husband','Wife','Kids','Cousin'])
df = df.sort_values(['B','A'], ignore_index=True)
print (df)
A B C
0 Husband Test1 $1200
1 Wife Test1 $1232
2 Kids Test1 $1288
3 Cousin Test1 $3265