[英]Python, Pandas. create a text file from a specific column
I am trying to create a text file from a column in a pandas dataframe.我正在尝试从 pandas dataframe 中的列创建一个文本文件。 There are repeating values and I'd like each value to only be copied once.
有重复的值,我希望每个值只复制一次。 I also do not want the row value in the text file.
我也不想要文本文件中的行值。
I have tried creating a dictionary:我试过创建一个字典:
stocks = dict(enumerate(df.tic.unique()))
then:然后:
f = open("stocks","w")
f.write( str(stocks) )
f.close()
The text file output is all the names, but I'd like each to have their own line.文本文件 output 是所有名称,但我希望每个名称都有自己的行。 Additionally, the row number is included which I need left out.
此外,还包括我需要省略的行号。
You're writing the string 'stocks'
to the file.您正在将字符串
'stocks'
写入文件。 You need to write the variable stocks
.您需要编写变量
stocks
。
saveFile = open('stocks', 'w')
saveFile.write(stocks)
saveFile.close()
I don't know what your dataframe looks like but here's an example.我不知道你的 dataframe 是什么样的,但这里有一个例子。
d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(d)
df["col1"].to_csv(r'data.txt', header=None, index=None, sep='\t', mode='a')
Replace the col1 in df["col1"]
with the name of your column and df by the name of your dataframe of course.当然,将
df["col1"]
中的 col1 替换为您的列名称,并将 df 替换为 dataframe 的名称。 IF you want to remove duplicates you could also simply use df.drop_duplicate(...) with the settings you want before saving your dataframe in the text file.如果您想删除重复项,您也可以在将 dataframe 保存在文本文件中之前简单地使用 df.drop_duplicate(...) 和所需的设置。
If you want to use unique()
, you can try this:如果你想使用
unique()
,你可以试试这个:
with open("stocks.txt", "w") as f:
f.write("\n".join(df.tic.unique()))
df.tic.unique()
returns the unique values of the column tic
df.tic.unique()
返回tic
列的唯一值"\n".join(df.tic.unique())
concatenates the unique values into a giant string, separated by new-line "\n".join(df.tic.unique())
将唯一值连接成一个巨大的字符串,用换行符分隔f.write
writes the giant string from 2 to the file f.write
将巨大的字符串从 2 写入文件I have also edited "stocks"
to "stocks.txt"
.我还将
"stocks"
编辑为"stocks.txt"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.