【问题标题】:how to change the type of the columns in a given dataframe using pandas and python如何使用 pandas 和 python 更改给定数据框中的列类型
【发布时间】:2021-08-05 10:19:04
【问题描述】:

如何创建一个函数来更改流光中数据框中列的 dtypes,其中用户选择他想要将所选列转换为它的类型?

我创建了一个将数据框作为参数的函数,而不是在下拉列表中显示用户可以从中选择的类型。

问题是当用户选择新类型并且系统打印df.info()时,所选列仍然具有旧类型。

代码:

import pandas as pd
import streamlit as st

def transform(df):
    types = {'-':None
           ,'Boolean': '?'
           ,'Byte': 'b'
           ,'Integer':'i'
           ,'Floating point': 'f' 
           ,'Date Time': 'M'
           ,'Time': 'm'
           ,'Unicode String':'U'
           ,'Object': 'O'}
    new_types = {}
    expander_types = st.beta_expander('Convert Data Types')
    for i, col in enumerate(df.columns):
        txt = 'Convert {} from {} to:'.format(col, df[col].dtypes)
        expander_types.markdown(txt, unsafe_allow_html=True)
        new_types[i] = expander_types.selectbox('Field to be converted:',[*types],index=0,key=i)
    st.text(" \n") #break line
    btn1 = st.button('Get CSV')
    if btn1:
        download_file(df, types, new_types, "csv")
        print("transform",df.info())
    

我的函数的错误在哪里??

【问题讨论】:

    标签: python pandas streamlit


    【解决方案1】:

    Pandas 可以将现有列中的数据转换为不同的数据类型。对于大多数字符串、整数、浮点数或布尔数据,使用pd.convert_dtypes,对于日期时间使用pd.to_datetime。如果您需要不转换数据类型的自定义输出(例如时间而不是日期时间),您可以使用 df.apply 和一个函数,该函数以原始形式输入数据并以您想要的形式输出数据。

    【讨论】:

    • 是的,我试图将一列转换为time 那么如何进行这种转换??
    • 您可以创建一个函数,以您想要的格式输入数据并输出时间,可能使用time.time()。然后可以将其与 df.apply 一起使用以创建新列。
    • ..to create a new column 或分配给现有列。
    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 2020-07-24
    • 2023-01-21
    • 1970-01-01
    • 2021-02-20
    • 2022-08-14
    • 2018-05-28
    • 2019-06-18
    相关资源
    最近更新 更多