【问题标题】:How to copy column header to other column in Pandas [closed]如何将列标题复制到熊猫中的其他列[关闭]
【发布时间】:2021-09-02 21:13:03
【问题描述】:

如何将一个列标题复制到同一 DataFrame 中的另一个列标题。并为python中的第二个标题添加后缀。
在我的数据中,我的标题是每月更改的月份。我想将该月自动复制到其他列。 谢谢

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

df.head()

   total  speeding  alcohol
0   18.8     7.332    5.640
1   18.1     7.421    4.525
2   18.6     6.510    5.208
3   22.4     4.032    5.824
4   12.0     4.200    3.360

添加新字段:

df["total_copy"] = df["total"]

   total  speeding  alcohol  total_copy
0   18.8     7.332    5.640        18.8
1   18.1     7.421    4.525        18.1
2   18.6     6.510    5.208        18.6
3   22.4     4.032    5.824        22.4
4   12.0     4.200    3.360        12.0

【讨论】:

    【解决方案2】:

    这是来自https://www.delftstack.com/howto/python-pandas/pandas-create-column-based-on-other-columns/的代码示例

     import pandas as pd
    
    items_df = pd.DataFrame({
        'Id': [302, 504, 708, 103, 343, 565],
        'Name': ['Watch', 'Camera', 'Phone', 'Shoes', 'Laptop', 'Bed'],
        'Actual Price': [300, 400, 350, 100, 1000, 400],
        'Discount(%)': [10, 15, 5, 0, 2, 7]
    })
    
    print("Initial DataFrame:")
    print(items_df, "\n")
    
    items_df['Final Price'] = items_df['Actual Price'] - \
        ((items_df['Discount(%)']/100) * items_df['Actual Price'])
    
    
    print("DataFrame after addition of new column")
    print(items_df, "\n")
    

    您可以为您的专栏应用相同的原则

    【讨论】:

    • 感谢您的回复。在此示例中,您正在定义列标题(最终价格),而不是复制另一个列标题。在我的数据中,我的标题是每月更改的月份。我想将该月自动复制到另一列。
    • @irfanraorao 你能分享一个例子吗?我不清楚是什么问题。
    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 2021-09-05
    • 2020-12-30
    • 2016-01-27
    • 2018-02-27
    • 2019-04-02
    • 2022-11-02
    • 1970-01-01
    相关资源
    最近更新 更多