[英]Pandas: how to write csv file using data from a dataframe as part of path/filename
Pandas: how to write csv file using data from a dataframe as part of path/filename Pandas:如何使用数据帧中的数据作为路径/文件名的一部分来编写csv文件
I have an example dataframe like this: 我有一个像这样的示例数据帧:
df = pd.DataFrame(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
print df
0
a -0.899348
b 0.297170
c -0.998461
d 0.651564
e 2.013107
and a second dataframe with a single column containing a full path/filename 以及包含完整路径/文件名的单列的第二个数据帧
data2 = {'filepath': ['C:\\test\\testsub\\testfile.csv']}
path = pd.DataFrame(data2, columns=['filepath'])
print path
filepath
0 C:\test\testsub\testfile.csv
I can write the first dataframe to a csv like this: 我可以将第一个数据帧写入csv,如下所示:
df.to_csv('C:\\test\\testsub\\testfile.csv')
But I can't find a way to set the path/filename from the 'path' dataframe. 但我找不到从'path'数据帧设置路径/文件名的方法。
df.to_csv(path['filepath'])
...returns an error: ...返回错误:
'TypeError: coercing to Unicode: need string or buffer, list found'
It seems the dataframe needs some form of conversion in order to be used here. 看来数据框需要某种形式的转换才能在这里使用。 I can't find any information on this.
我找不到任何关于此的信息。 Can anybody enlighten me as to how I can make this work?
任何人都可以告诉我如何使这项工作? Any and all help appreciated.
任何和所有帮助表示赞赏。
(In the bigger picture, the process is part of a loop where the required path/filename is returned in the dataframe 'path'. I can print the path and filename exactly as they should be, but I can't write the csv) (在更大的图片中,该过程是循环的一部分,其中在数据帧'路径'中返回所需的路径/文件名。我可以完全按原样打印路径和文件名,但我不能写csv)
You just need to make sure that you're extracting a single element from the filepath
column, rather that passing the whole column as the filename. 您只需要确保从文件
filepath
列中提取单个元素,而不是将整个列作为文件名传递。 You can do this with an indexing method like .ix[]
or .iloc[]
: 您可以使用
.ix[]
或.iloc[]
等索引方法执行此操作:
current_filepath = path['filepath'].iloc[0]
current_filepath
Out[8]: 'C:\\test\\testsub\\testfile.csv'
df.to_csv(current_filepath)
Because your example dataframe path
just has integer indexes, you can also just do: 因为您的示例数据帧
path
只有整数索引,所以您也可以这样做:
path['filepath'][0]
but this won't work the same way if you have a different index. 但如果你有不同的索引,这将不会以相同的方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.