Numpy Array 没有将数组的所有值复制到 csv 文件
Numpy Array is not copying over all values of the array to csv file
我在将数组保存到 csv 文件时遇到格式化问题,每次我 运行 程序都得到不同的结果,有时不显示字符串“creditCard”在传播 sheet 但所有其他细节都是。有时是这样。我的代码中是否有明显的原因导致这种不稳定?我已附上相关代码
def start():
dtype = [('Name', (np.str_, 10 )), ('Number of uses', np.int32), ('Card Value', np.float64)]
defaultCardArray = np.array([("creditCard",4,200)],dtype=dtype)
np.savetxt('creditCards.csv', defaultCardArray, delimiter=',', fmt=['%s' , '%d', '%f'],
header='Name,Number of Uses, Card Value', comments='')e here
创建文件后,我还有以下代码可以在之后添加每张卡片。默认卡在文件创建时加载正常,但以下卡阵列是我遇到的问题
有代码要求用户输入并保存到变量而不会出错,所以我没有在此处包含它
cardArray = np.array([creditCard,itemLimit,cardValueInput]).reshape(1,3)
file = open(r'creditCards.csv', 'at', newline ='')
with file:
write = csv.writer(file)
write.writerows(cardArray)
file.close()
image of the output I am getting in the csv
对于您的代码,我认为当您创建新的 cardArray
时,您没有像为初始数组那样指定类型,这可能是个问题。
无论如何,numpy 可能不是这里使用的最佳库。
对于这种数据,我会使用 pandas:
import pandas as pd
header = ['Name', 'Number of Uses', 'Card Value']
def start():
# create default dataset
default_card_df = pd.DataFrame(["creditCard",4,200], columns=header)
default_card_df.to_csv('creditCards.csv', sep=",")
def add_card(name, itemLimit, cardValueInput):
# read csv, add new data, save to csv
df = pd.read_csv('creaditCards.csv', sep=",")
new_df = pd.DataFrame([name, itemLimit, cardValueInput], columns=header)
updated_df = pd.concat(df, new_df)
updated_df.to_csv('creditCards.csv', sep=",")
您的初始写作:
In [281]: np.savetxt('creditCards.csv', defaultCardArray, delimiter=',', fmt=['%
...: s' , '%d', '%f'],
...: header='Name,Number of Uses, Card Value', comments='')
产生:
In [282]: cat creditCards.csv
Name,Number of Uses, Card Value
creditCard,4,200.000000
如果以追加模式打开,我们可以向该文件添加更多条目:
In [284]: with open('creditCards.csv','a') as f:
...: np.savetxt(f, defaultCardArray, delimiter=',', fmt=['%s' , '%d', '
...: %f'])
...:
In [285]: cat creditCards.csv
Name,Number of Uses, Card Value
creditCard,4,200.000000
creditCard,4,200.000000
要继续使用具有相同 fmt
的 savetxt
,您应该使用原始 dtype
.
创建数组
.
In [286]: newcards = np.zeros(3,dtype=dtype)
In [287]: newcards
Out[287]:
array([('', 0, 0.), ('', 0, 0.), ('', 0, 0.)],
dtype=[('Name', '<U10'), ('Number of uses', '<i4'), ('Card Value', '<f8')])
In [289]: newcards['Name']='foobar'
In [290]: newcards['Card Value']=np.arange(10,40,10)
In [291]: newcards
Out[291]:
array([('foobar', 0, 10.), ('foobar', 0, 20.), ('foobar', 0, 30.)],
dtype=[('Name', '<U10'), ('Number of uses', '<i4'), ('Card Value', '<f8')])
In [292]: with open('creditCards.csv','a') as f:
...: np.savetxt(f, newcards, delimiter=',', fmt=['%s' , '%d', '%f'])
...:
In [293]: cat creditCards.csv
Name,Number of Uses, Card Value
creditCard,4,200.000000
creditCard,4,200.000000
foobar,0,10.000000
foobar,0,20.000000
foobar,0,30.000000
我在将数组保存到 csv 文件时遇到格式化问题,每次我 运行 程序都得到不同的结果,有时不显示字符串“creditCard”在传播 sheet 但所有其他细节都是。有时是这样。我的代码中是否有明显的原因导致这种不稳定?我已附上相关代码
def start():
dtype = [('Name', (np.str_, 10 )), ('Number of uses', np.int32), ('Card Value', np.float64)]
defaultCardArray = np.array([("creditCard",4,200)],dtype=dtype)
np.savetxt('creditCards.csv', defaultCardArray, delimiter=',', fmt=['%s' , '%d', '%f'],
header='Name,Number of Uses, Card Value', comments='')e here
创建文件后,我还有以下代码可以在之后添加每张卡片。默认卡在文件创建时加载正常,但以下卡阵列是我遇到的问题 有代码要求用户输入并保存到变量而不会出错,所以我没有在此处包含它
cardArray = np.array([creditCard,itemLimit,cardValueInput]).reshape(1,3)
file = open(r'creditCards.csv', 'at', newline ='')
with file:
write = csv.writer(file)
write.writerows(cardArray)
file.close()
image of the output I am getting in the csv
对于您的代码,我认为当您创建新的 cardArray
时,您没有像为初始数组那样指定类型,这可能是个问题。
无论如何,numpy 可能不是这里使用的最佳库。
对于这种数据,我会使用 pandas:
import pandas as pd
header = ['Name', 'Number of Uses', 'Card Value']
def start():
# create default dataset
default_card_df = pd.DataFrame(["creditCard",4,200], columns=header)
default_card_df.to_csv('creditCards.csv', sep=",")
def add_card(name, itemLimit, cardValueInput):
# read csv, add new data, save to csv
df = pd.read_csv('creaditCards.csv', sep=",")
new_df = pd.DataFrame([name, itemLimit, cardValueInput], columns=header)
updated_df = pd.concat(df, new_df)
updated_df.to_csv('creditCards.csv', sep=",")
您的初始写作:
In [281]: np.savetxt('creditCards.csv', defaultCardArray, delimiter=',', fmt=['%
...: s' , '%d', '%f'],
...: header='Name,Number of Uses, Card Value', comments='')
产生:
In [282]: cat creditCards.csv
Name,Number of Uses, Card Value
creditCard,4,200.000000
如果以追加模式打开,我们可以向该文件添加更多条目:
In [284]: with open('creditCards.csv','a') as f:
...: np.savetxt(f, defaultCardArray, delimiter=',', fmt=['%s' , '%d', '
...: %f'])
...:
In [285]: cat creditCards.csv
Name,Number of Uses, Card Value
creditCard,4,200.000000
creditCard,4,200.000000
要继续使用具有相同 fmt
的 savetxt
,您应该使用原始 dtype
.
.
In [286]: newcards = np.zeros(3,dtype=dtype)
In [287]: newcards
Out[287]:
array([('', 0, 0.), ('', 0, 0.), ('', 0, 0.)],
dtype=[('Name', '<U10'), ('Number of uses', '<i4'), ('Card Value', '<f8')])
In [289]: newcards['Name']='foobar'
In [290]: newcards['Card Value']=np.arange(10,40,10)
In [291]: newcards
Out[291]:
array([('foobar', 0, 10.), ('foobar', 0, 20.), ('foobar', 0, 30.)],
dtype=[('Name', '<U10'), ('Number of uses', '<i4'), ('Card Value', '<f8')])
In [292]: with open('creditCards.csv','a') as f:
...: np.savetxt(f, newcards, delimiter=',', fmt=['%s' , '%d', '%f'])
...:
In [293]: cat creditCards.csv
Name,Number of Uses, Card Value
creditCard,4,200.000000
creditCard,4,200.000000
foobar,0,10.000000
foobar,0,20.000000
foobar,0,30.000000