pandas to \u csv通过添加换行符或在datafram中存储numpy数组来更改数据

2024-03-28 22:11:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我用一些数据(一些是numpy数组)生成一个pandas数据帧,并用pandas.to\u csv功能。在

但是,当使用熊猫阅读我注意到pandas在numpy数组中添加了换行符,如下所示(参见最后的输出)

import pandas as pd
import numpy as np


# In[34]:
# create the dataframe
d = {'col1': [1, 2], 'col2': [3, 4]}
df=pd.DataFrame(data=d)
df.head()

输出:

^{pr2}$
# In[35]:
# append array data to dataframe
data = np.array([])
data = np.zeros(512)
df = df.append({'col1' : data },  ignore_index=True)
df.head()


# In[37]:
# write to csv
df.to_csv('records.csv')

#read csv
df= pd.read_csv('records.csv')
df.head()


# In[40]:
array = df['col1'].values
print(array)

出[]: ['1''2' [0'。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000.0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。00000000000000000000000。\n 0。0000000.]']

有什么办法解决这个问题或者为什么会发生这种情况?在

感谢您的评论,我包括了一个例子,复制了这个问题,并重新措辞的问题,因为似乎我要做的是存储一个numpy数组在一个数据帧单元。在


Tags: csvto数据inimportnumpypandasdf
1条回答
网友
1楼 · 发布于 2024-03-28 22:11:43

我们就是这样解决这个问题的。在

array_list = np.array([])
for i in array:
    data_tmp = np.fromstring(i[1:-1],dtype=np.float,sep=' ')
    array_list = np.concatenate([array_list, data_tmp])
array_list = array_list.reshape((1,-1))

print(array_list)

[出去]

[[0。00000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 000000000000000000000000 00000000.]]

相关问题 更多 >