gpt4 book ai didi

python - 将 Pandas 数据框中的两列分成两列并命名

转载 作者:行者123 更新时间:2023-12-04 01:11:17 24 4
gpt4 key购买 nike

我有这个 Pandas 数据框

         x           y       Values
0 A B C D 4.7
1 A B C D 10.9
2 A B C D 1.8
3 A B C D 6.5
4 A B C D 3.4

我想拆分 x 和 y 列并在列上获得具有这些给定名称的输出。

     x    f    y    g   Values
0 A B C D 4.7
1 A B C D 10.9
2 A B C D 1.8
3 A B C D 6.5
4 A B C D 3.4

在 python 中是否有直接的方法来执行此操作?

最佳答案

df[['x', 'f']] = df.x.str.split(" ", expand=True)
df[['y', 'g']] = df.y.str.split(" ", expand=True)
df[['x','f','y','g', 'Values']]

您也可以使其具有可扩展性,定义一个字典,其中的键是列,值是一个包含所需新列名称的列表:

# Define the target columns to split, and their new column names
cols={
'x': ['x','f'],
'y': ['y','g']
}
# Apply the function to each target-column
for k in cols:
df[cols[k]] = df[k].str.split(" ", expand=True)

# Reorder the dataframe as you wish
new_columns = sum(cols.values(),[])
old_columns = set(df.columns) - set(new_columns)
df[new_columns + list(old_columns)]

关于python - 将 Pandas 数据框中的两列分成两列并命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64773001/

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