我有一个以下的数据框-
0
____________________________________
0 Country| India
60 Delhi
62 Mumbai
68 Chennai
75 Country| Italy
78 Rome
80 Venice
85 Milan
88 Country| Australia
100 Sydney
103 Melbourne
107 Perth
我想将数据分为两列,以便在一列中有国家,在另一列中有城市。我不知道从哪里开始。我想像下面
0 1
____________________________________
0 Country| India Delhi
1 Country| India Mumbai
2 Country| India Chennai
3 Country| Italy Rome
4 Country| Italy Venice
5 Country| Italy Milan
6 Country| Australia Sydney
7 Country| Australia Melbourne
8 Country| Australia Perth
任何想法如何做到这一点?
DataFrame.insert
与Series.where
和Series.str.startswith
一起使用,用于将不匹配的值替换为,ffill
以向前填充缺失的值,然后通过删除Series.ne
不相等的值来删除两者中具有相同值的行boolean indexing
:
df.insert(0, 'country', df[0].where(df[0].str.startswith('Country')).ffill())
df = df[df['country'].ne(df[0])].reset_index(drop=True).rename(columns={0:'city'})
print (df)
country city
0 Country|India Delhi
1 Country|India Mumbai
2 Country|India Chennai
3 Country|Italy Rome
4 Country|Italy Venice
5 Country|Italy Milan
6 Country|Australia Sydney
7 Country|Australia Melbourne
8 Country|Australia Perth
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句