如何创建一个函数来更改Streamlight中数据帧中列的数据类型,用户可以在其中选择要将所选列转换为该列的类型
我创建了一个以dataframe为参数的函数,然后在下拉列表中显示用户可以从中选择的类型
问题是,当用户选择新类型并且系统打印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())
我的函数中的错误在哪里
熊猫可以将现有列中的数据转换为不同的数据类型。对于大多数字符串、整数、浮点或布尔数据,使用pd.convert_dtypes,对于日期时间,使用pd.to_datetime。如果需要不转换数据类型的自定义输出(如time而不是datetime),可以将df.apply与函数一起使用,以原始形式输入数据,并以所需的形式输出数据
相关问题 更多 >
编程相关推荐