如何打开此DataFrame
的第一列,该列是字符串和整数混合
df = pd.DataFrame(
[
["title1", "a", "b", "c", "d"],
[1, 2, 3, 4, 5],
[10, 2, 3, 4, 5],
[100, 2, 3, 4, 5],
["title2", "a", "b", "c", "d"],
[1, 2, 3, 4, 5],
[10, 2, 3, 4, 5],
[100, 2, 3, 4, 5],
["title3", "a", "b", "c", "d"],
[1, 2, 3, 4, 5],
[10, 2, 3, 4, 5],
[100, 2, 3, 4, 5],
]
)
看起来像这样
title1 a b c d
1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
title2 a b c d
1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
title3 a b c d
1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
放入MultiIndex
,其中顶层是字符串,第二层是整数?
a b c d
title1 1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
title2 1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
title3 1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
答案 0 :(得分:2)
使用:
#get mask for distingusih strings values in column 0
m = pd.to_numeric(df[0], errors='coerce').isna()
#alternative
#m = ~df[0].astype(str).str.isnumeric()
#create new column 0 filled with strings
df.insert(0, 'a', df[0].where(m).ffill())
#mask for filter not same values in both columns
m1 = df['a'].ne(df[0])
#create MultiIndex
df = df.set_index(['a', 0])
#assign new columns names by first row
df.columns = df.iloc[0]
#filter out by mask and remove index, columns names
df = df[m1.values].rename_axis((None, None)).rename_axis(None, axis=1)
print (df)
a b c d
title1 1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
title2 1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
title3 1 2 3 4 5
10 2 3 4 5
100 2 3 4 5
答案 1 :(得分:1)
此类问题的关键是创建一个布尔级数,以标识level_0索引的位置
<Picker>
{ this.state.data.map((item)=> <Item label={item} value={item} />) }
<Picker>