xAp*_*ple 29 python csv dataframe pandas
我有一个pandas.DataFrame我想导出到CSV文件.但是,熊猫似乎写了一些值float而不是int类型.我无法找到如何改变这种行为.
构建数据框:
df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'], dtype=int)
x = pandas.Series([10,10,10], index=['a','b','d'], dtype=int)
y = pandas.Series([1,5,2,3], index=['a','b','c','d'], dtype=int)
z = pandas.Series([1,2,3,4], index=['a','b','c','d'], dtype=int)
df.loc['x']=x; df.loc['y']=y; df.loc['z']=z
Run Code Online (Sandbox Code Playgroud)
查看它:
>>> df
a b c d
x 10 10 NaN 10
y 1 5 2 3
z 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
出口它:
>>> df.to_csv('test.csv', sep='\t', na_rep='0', dtype=int)
>>> for l in open('test.csv'): print l.strip('\n')
a b c d
x 10.0 10.0 0 10.0
y 1 5 2 3
z 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
为什么十位点零?
当然,我可以将此功能粘贴到我的管道中以重新转换整个CSV文件,但似乎没有必要:
def lines_as_integer(path):
handle = open(path)
yield handle.next()
for line in handle:
line = line.split()
label = line[0]
values = map(float, line[1:])
values = map(int, values)
yield label + '\t' + '\t'.join(map(str,values)) + '\n'
handle = open(path_table_int, 'w')
handle.writelines(lines_as_integer(path_table_float))
handle.close()
Run Code Online (Sandbox Code Playgroud)
xAp*_*ple 14
我正在寻找的答案是@Jeff在他的回答中提出的一点点变化.归功于他.这就是我最终解决了我的问题以供参考:
import pandas
df = pandas.DataFrame(data, columns=['a','b','c','d'], index=['x','y','z'])
df = df.fillna(0)
df = df.astype(int)
df.to_csv('test.csv', sep='\t')
Run Code Online (Sandbox Code Playgroud)
And*_*den 12
这是pandas中的"陷阱"(支持整数NA),其中带有NaN的整数列被转换为浮点数.
这种权衡主要是出于内存和性能的原因,也是为了使得最终的系列继续"数字化".一种可能性是使用
dtype=object数组.
问题在于,由于您按行分配事物,但dtypes按列分组,因此事物会被转换为objectdtype,这不是一件好事,您会失去所有效率.所以一种方法是转换哪个将根据需要强制浮动/ int dtype.
正如我们在另一个问题中回答的那样,如果您一次构建框架(或逐列构造),则不需要此步骤
In [23]: def convert(x):
....: try:
....: return x.astype(int)
....: except:
....: return x
....:
In [24]: df.apply(convert)
Out[24]:
a b c d
x 10 10 NaN 10
y 1 5 2 3
z 1 2 3 4
In [25]: df.apply(convert).dtypes
Out[25]:
a int64
b int64
c float64
d int64
dtype: object
In [26]: df.apply(convert).to_csv('test.csv')
In [27]: !cat test.csv
,a,b,c,d
x,10,10,,10
y,1,5,2.0,3
z,1,2,3.0,4
Run Code Online (Sandbox Code Playgroud)
最简单的解决方案是float_format使用pd.read_csv():
df.to_csv('test.csv', sep='\t', na_rep=0, float_format='%.0f')
Run Code Online (Sandbox Code Playgroud)
但这适用于所有浮动列。顺便说一句:在 pandas 1.1.5 上使用您的代码,我的所有列都是浮动的。
输出:
a b c d
x 10 10 0 10
y 1 5 2 3
z 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
没有float_format:
a b c d
x 10.0 10.0 0 10.0
y 1.0 5.0 2.0 3.0
z 1.0 2.0 3.0 4.0
Run Code Online (Sandbox Code Playgroud)
如果要在导出的 csv 中保留 NaN 信息,请执行以下操作。PS:在这种情况下,我专注于“C”列。
df[c] = df[c].fillna('') #filling Nan with empty string
df[c] = df[c].astype(str) #convert the column to string
>>> df
a b c d
x 10 10 10
y 1 5 2.0 3
z 1 2 3.0 4
df[c] = df[c].str.split('.') #split the float value into list based on '.'
>>> df
a b c d
x 10 10 [''] 10
y 1 5 ['2','0'] 3
z 1 2 ['3','0'] 4
df[c] = df[c].str[0] #select 1st element from the list
>>> df
a b c d
x 10 10 10
y 1 5 2 3
z 1 2 3 4
Run Code Online (Sandbox Code Playgroud)
现在,如果您将数据框导出到 csv,列 'c' 将没有浮点值并且 NaN 信息被保留。
| 归档时间: |
|
| 查看次数: |
31264 次 |
| 最近记录: |