gpt4 book ai didi

python - Pandas 数据框

转载 作者:行者123 更新时间:2023-12-04 15:14:12 26 4
gpt4 key购买 nike

我有一个包含许多列和行的数据框,在除了最左边的两列之外的所有列中,都有“整数-整数”形式的数据。我想将所有这些列拆分为两列,每个整数在其自己的单元格中,并删​​除破折号。

我尝试按照 Pandas Dataframe: Split multiple columns each into two columns 中的答案进行操作,但似乎它们在一个元素之后 split ,而我想在“-”上 split 。

例如,假设我有一个以下形式的数据框:

enter image description here

我想将标记为 2 的列拆分为 22,将它们命名为 2F、2A、3F、3A、...、6A,第一行中的数据为 R1、Hawthorn、229、225、91 , 81, ..., 12.

感谢您的帮助。

最佳答案

您可以使用 DataFrame.set_indexDataFrame.stack对于 Series,然后按 Series.str.split 拆分为新的 2 列,转换为整数,通过 DataFrame.set_axis 创建新的列名, 通过 DataFrame.unstack reshape ,按 DataFrame.sort_index 对列进行排序最后通过 DataFrame.reset_index 将索引转换为列来展平 MultiIndex :

#first replace columns names to default values
df.columns = range(len(df.columns))

df = (df.set_index([0,1])
.stack()
.str.split('-', expand=True)
.astype(int)
.set_axis(['F','A'], axis=1, inplace=False)
.unstack()
.sort_index(axis=1, level=[1,0], ascending=[True, False]))
df.columns = df.columns.map(lambda x: f'{x[1]}{x[0]}')
df = df.reset_index()
print (df)
0 1 2F 2A 3F 3A 4F 4A 5F 5A 6F 6A
0 R1 Hawthorn 229 225 91 81 216 142 439 367 7 12
1 R2 Sydney 226 214 93 92 151 167 377 381 12 8
2 R3 Geelong 216 228 91 166 159 121 369 349 16 14
3 R4 North Melbourne 213 239 169 126 142 155 355 394 8 9
4 R5 Gold Coast 248 226 166 94 267 169 455 389 18 6
5 R6 St Kilda 242 197 118 161 158 156 466 353 15 16
6 R7 Fremantle 225 219 72 84 224 185 449 464 7 5

关于python - Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64619132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com