'convert column to comma seperarted string with python
I have a data frame as:
id. name
123 sanfrancisco
124 losangeles
12356 washington
123441 orlando
I need to convert this name column into comma sep string value as:
'san francisco', 'losangeles', 'washington', 'orlando'
I've changed this into list but i cannot use array, i need string value.
thanks
Solution 1:[1]
', '.join(df.name.to_list())
'sanfrancisco, losangeles, washington, orlando'
Edit:
If you need the quotes:
', '.join(df.name.apply("'{}'".format).to_list())
'sanfrancisco', 'losangeles', 'washington', 'orlando'
Solution 2:[2]
import os
os.getcwd()
returns current working path. You can use it as a variable to output path.
You should ask users of the script to have the source Excel file in the same path as your .py file;
If I understood you correctly, this should help.
Solution 3:[3]
If you think the users are going to be non-technical, you can use a tkinter window to choose the files. For eg, the below code gets the 2 file paths, and then you can work with it.
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
source_file_path = filedialog.askopenfilename(title="Choose source file")
target_file_path = filedialog.askopenfilename(title="Choose target file")
There are options, to filter file types, starter directory etc, for that you can refer the documentation.
Solution 4:[4]
I would use tkinter.filedialog for this task, consider following simple example
import tkinter as tk
from tkinter import filedialog
filepath1 = ""
def callback():
global filepath1
filepath1 = filedialog.askopenfilename()
root.destroy()
root = tk.Tk()
btn = tk.Button(root, text="Click to select file", command=callback)
btn.pack()
tk.mainloop()
print("User selected", filepath1)
If you are allowed to use external modules as you wish, then you might use easygui as follows
import easygui
filepath = easygui.fileopenbox("Select file")
print("User selected", filepath)
In order to install easygui just do pip install easygui
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Niqua |
| Solution 3 | Kris |
| Solution 4 |
