pandas 数据框保存到csv文件中 [英] Pandas Data Frame saving into csv file

查看:98
本文介绍了 pandas 数据框保存到csv文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将新的pandas系列保存到另一列的csv文件中.假设我有两个csv文件,两个文件都包含一列"A".我已经对它们完成了一些数学功能,然后创建了一个新变量"B".

I wonder how to save a new pandas Series into a csv file in a different column. Suppose I have two csv files which both contains a column as a 'A'. I have done some mathematical function on them and then create a new variable as a 'B'.

例如:

data = pd.read_csv('filepath')

data['B'] = data['A']*10

# and add the value of data.B into a list as a B_list.append(data.B) 

此操作将一直持续到第一个和第二个csv文件的所有行都已读取为止.

This will continue until all of the rows of the first and second csv file has been reading.

我想从两个csv文件中将B列保存在新的电子表格中. 例如,我需要以下结果:

I would like to save a column B in a new spread sheet from both csv files. For example I need this result:

colum1(from csv1)        colum2(from csv2)     
     data.B.value             data.b.value

通过使用以下代码:

pd.DataFrame(np.array(B_list)).T.to_csv('file.csv', index=False, header=None)

我不会得到我想要的结果.

I won't get my preferred result.

推荐答案

由于熊猫DataFrame中的每一列都是熊猫Series.您的 B_list 实际上是熊猫Series的列表,您可以将其转换为DataFrame()构造函数,然后转置(或@jezrael显示与pd.concat(..., axis=1)的水平合并)

Since each column in a pandas DataFrame is a pandas Series. Your B_list is actually a list of pandas Series which you can cast to DataFrame() constructor, then transpose (or as @jezrael shows a horizontal merge with pd.concat(..., axis=1))

finaldf = pd.DataFrame(B_list).T
finaldf.to_csv('output.csv', index=False, header=None)

并且如果csv具有不同的行,则在对应的行中用NAN填充不相等的序列.

And should csv have different rows, unequal series are filled with NANs at corresponding rows.

这篇关于 pandas 数据框保存到csv文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆