Python pandas系列:将float转换为string,保留空值

时间:2017-03-30 18:29:17

标签: python pandas numpy

如何在转换为字符串后保留空值?我正在使用社会安全号码,有必要在浮动和字符串之间来回。

import pandas as pd
import numpy as np    
x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull()

...有空值

y = x.astype(str)
y.isnull()

...没有空值

理想情况下,x.isnull()和y.isnull()将是相同的。

我认为使用一系列混合dtypes是危险的,但认为这是目前最好的解决方案:

z = y.copy()
z[z == 'nan'] = np.nan
z.isnull() # works as desired
type(z[0]) # but has floats for nulls
type(z[1]) # and strings for values

5 个答案:

答案 0 :(得分:2)

我也遇到了这个问题,但是对于DataFrames。适用于pandas系列和DataFrame的一种方法是使用mask():

data = pd.Series([np.NaN, 10, 30, np.NaN]) # Also works for pd.DataFrame
null_cells = data.isnull()
data = data.astype(str).mask(null_cells, np.NaN)

答案 1 :(得分:1)

如果您将import pandas as pd import matplotlib.pyplot as plt df = pd.read_excel('SAT_data.xlsx', index_col = 'State') plt.figure() plt.scatter(df['Year'], df['Reading'], c = 'blue', s = 25) plt.scatter(df['Year'], df['Math'], c = 'orange', s = 25) plt.scatter(df['Year'], df['Writing'], c = 'red', s = 25) 转换为np.nan,它将变为字符串str'nan'将像其他字符串一样处理。

关于你的编辑:转换为str值后,你需要定义什么字符串是" null"依你的意见。一种方法可能是:

isnull

这至少会给你想要的结果。

答案 2 :(得分:1)

你可以强制转换为字符串,条件是不为空。

%matplotlib inline
import matplotlib.pyplot as plt

stLen = iris[Species=='setosa']['Petal.Length']
stWid = iris[Species=='setosa']['Petal.Width']

vsLen = iris[Species=='versicolor']['Petal.Length']
vsWid = iris[Species=='versicolor']['Petal.Width']

viLen = iris[Species=='virginica']['Petal.Length']
viWid = iris[Species=='virginica']['Petal.Width']

plt.rcParams['figure.figsize'] = 8, 6
plt.rc('axes',edgecolor='black')

fntsz = 12  # global font size adjustment

sctplt1 = plt.scatter(stLen, stWid, c='blue',   alpha=0.8) 
sctplt2 = plt.scatter(vsLen, vsWid, c='red',    alpha=0.8)  
sctplt3 = plt.scatter(viLen, viWid, c='purple', alpha=0.8)

plt.legend((sctplt1, sctplt2, sctplt3),
           ('setosa', 'versicolor', 'virginica'),
           scatterpoints=3,
           loc='upper left',
           ncol=1,
           fontsize=10, frameon=True).get_frame().set_edgecolor('black')
                        # help claimed edgecolor should be legend() argument but errors say otherwise
                        # .getframe().set_edgecolor() was supposed to do it but its not working

plt.title('Iris', fontsize = fntsz)     # defaults to center ... to change this:  plt.title('title', loc='right' | 'left')
plt.xlabel('Petal Length', fontsize = fntsz)
plt.ylabel('Petal Width', fontsize = fntsz)

# turn off grid lines:
plt.grid(b=False)

# to save to a file
# fig.savefig('test.jpg')

plt.show

答案 3 :(得分:0)

使用系列仅将非空值转换为str:

y = x.where(x.isnull(), x.astype(str))
y.isnull()

答案 4 :(得分:0)

由于某些原因,当您使用Series.astype(str)转换系列时,np.NaN会转换为字符串'nan',但使用dtype=str创建新系列时则不会。因此,以下方法将起作用:

x_str = pd.Series([np.nan, 123., np.nan, 456.], dtype = str)
x_str.isnull() # Has nulls as expected

知道这一点后,我们可以使用Series构造函数将现有系列转换为字符串,同时保留空值:

x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull() 
y1 = pd.Series(x.array, dtype=str)
y1.isnull() # Has nulls as expected

请注意,为了使此功能起作用,您需要将数组或列表传递给Series构造函数(在当前示例中,这意味着调用x.arrayx.values)。如果通过系列,则将转换空值,就像调用astype()

一样
y2 = pd.Series(x, dtype=str)  # x is a series
y2.isnull()  # Nulls converted to 'nan'