在 python 中用用户输入值填充空白单元格后 DataFrame 列类型发生变化
DataFrame column type changes after filling blank cell with user input value in python
我有一个很大的 excel 文件上传到 spyder,只是为了一个例子。我让它变得简单 -
Date Name Project Age Pin_code Remarks Gender
0 2020-01-01 a proj_a 34 123456 grade_a M
1 2019-12-04 b proj_b 48 789012
2 c 54 M
现在我需要用用户输入值填充空白单元格(仅字符串列),假设用户输入 - 'no_entry'
,然后在我需要的所有字符串列中将此值填充到空白单元格,对于数字列,我需要填写 0
,对于日期时间列,我需要填写 - 0000-00-00
。我面临的问题是 - 插入后,日期最初看起来像 - 2020-01-01
插入后它变成 - 2020-01-01 00:00:00
并且它只将 0 分配给空白单元格, pin_code 列变为浮动喜欢 - 789012.0
。如何避免这些障碍,请帮助。
我的代码-
import pandas as pd
import numpy as np
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
from pandas.api.types import is_datetime64_dtype
ip = input('Please enter a value for blank cells : ')
col = df.columns
for c in col:
if is_string_dtype(df[c]) == True:
df[c].fillna(ip, inplace = True)
if is_integer_dtype(df[c]) == True :
df[c].fillna(0, inplace = True)
if is_datetime64_dtype(df[c]) == True:
df[c].fillna(0000-00-00, inplace = True)
如果不需要有效的 pandas 日期时间 - 0000-00-00
是必要的,将日期转换为字符串,将数字转换为整数使用 astype(int)
ip = input('Please enter a value for blank cells : ')
for c in df.columns:
if is_string_dtype(df[c]):
df[c].fillna(ip, inplace = True)
if is_numeric_dtype(df[c]):
df[c] = df[c].fillna(0).astype(int)
if is_datetime64_dtype(df[c]):
df[c] = df[c].dt.strftime('%Y-%m-%d').fillna('0000-00-00')
我有一个很大的 excel 文件上传到 spyder,只是为了一个例子。我让它变得简单 -
Date Name Project Age Pin_code Remarks Gender
0 2020-01-01 a proj_a 34 123456 grade_a M
1 2019-12-04 b proj_b 48 789012
2 c 54 M
现在我需要用用户输入值填充空白单元格(仅字符串列),假设用户输入 - 'no_entry'
,然后在我需要的所有字符串列中将此值填充到空白单元格,对于数字列,我需要填写 0
,对于日期时间列,我需要填写 - 0000-00-00
。我面临的问题是 - 插入后,日期最初看起来像 - 2020-01-01
插入后它变成 - 2020-01-01 00:00:00
并且它只将 0 分配给空白单元格, pin_code 列变为浮动喜欢 - 789012.0
。如何避免这些障碍,请帮助。
我的代码-
import pandas as pd
import numpy as np
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
from pandas.api.types import is_datetime64_dtype
ip = input('Please enter a value for blank cells : ')
col = df.columns
for c in col:
if is_string_dtype(df[c]) == True:
df[c].fillna(ip, inplace = True)
if is_integer_dtype(df[c]) == True :
df[c].fillna(0, inplace = True)
if is_datetime64_dtype(df[c]) == True:
df[c].fillna(0000-00-00, inplace = True)
如果不需要有效的 pandas 日期时间 - 0000-00-00
是必要的,将日期转换为字符串,将数字转换为整数使用 astype(int)
ip = input('Please enter a value for blank cells : ')
for c in df.columns:
if is_string_dtype(df[c]):
df[c].fillna(ip, inplace = True)
if is_numeric_dtype(df[c]):
df[c] = df[c].fillna(0).astype(int)
if is_datetime64_dtype(df[c]):
df[c] = df[c].dt.strftime('%Y-%m-%d').fillna('0000-00-00')