如何保存然后从数据框中的文件名中提取一些信息
how to save and then extract some information from the file names in dataframe
我在一个路径中有将近 1000000 个甚至更多的文件。
我的最终目标是仅从 names
个文件中提取一些信息。
到目前为止,我已经将文件名保存在列表中。
文件名中包含哪些信息?
所以文件名的格式是这样的:
09066271_142468576_1_Haha_-Haha-haha_2016-10-07_haha-false_haha2427.txt
哈哈都是其他无所谓的不同文字
我想从名称中提取 09066271
和 2016-10-07
并保存在数据框中。第一个数字总是 8 个字符。
到目前为止,我已经将整个文本文件名保存在列表中:
path = 'path to the saved txt files/fldr'
file_list = os.listdir(path)
首先我想将整个 txt 文件名保存在数据框中,然后对它们进行这些操作。看来我必须首先阅读 numpy,然后将其重塑为在 pandas 中可读。但是我现在不知道重塑数字是多少。
df = pd.DataFrame(np.array(file_list).reshape(,))
如果你能告诉我你的想法以及这样做的有效方法,我将不胜感激:)
您可以使用os
列出所有文件。然后只需构造一个 DataFrame
并使用字符串方法来获取您需要的文件名部分。
import pandas as pd
import os
path = 'path to the saved txt files/fldr'
file_list = os.listdir(path)
df = pd.DataFrame(file_list, columns=['file_name'])
df['data'] = df.file_name.str[0:8]
df['date'] = df.file_name.str.extract('(\d{4}-\d{2}-\d{2})', expand=True)
file_name data date
0 09066271_142468576_1_Haha_-Haha-haha_2016-10-0... 09066271 2016-10-07
1 09014271_142468576_1_Haha_-Haha-haha_2013-02-1... 09014271 2013-02-18
我在一个路径中有将近 1000000 个甚至更多的文件。
我的最终目标是仅从 names
个文件中提取一些信息。
到目前为止,我已经将文件名保存在列表中。
文件名中包含哪些信息?
所以文件名的格式是这样的:
09066271_142468576_1_Haha_-Haha-haha_2016-10-07_haha-false_haha2427.txt
哈哈都是其他无所谓的不同文字
我想从名称中提取 09066271
和 2016-10-07
并保存在数据框中。第一个数字总是 8 个字符。
到目前为止,我已经将整个文本文件名保存在列表中:
path = 'path to the saved txt files/fldr'
file_list = os.listdir(path)
首先我想将整个 txt 文件名保存在数据框中,然后对它们进行这些操作。看来我必须首先阅读 numpy,然后将其重塑为在 pandas 中可读。但是我现在不知道重塑数字是多少。
df = pd.DataFrame(np.array(file_list).reshape(,))
如果你能告诉我你的想法以及这样做的有效方法,我将不胜感激:)
您可以使用os
列出所有文件。然后只需构造一个 DataFrame
并使用字符串方法来获取您需要的文件名部分。
import pandas as pd
import os
path = 'path to the saved txt files/fldr'
file_list = os.listdir(path)
df = pd.DataFrame(file_list, columns=['file_name'])
df['data'] = df.file_name.str[0:8]
df['date'] = df.file_name.str.extract('(\d{4}-\d{2}-\d{2})', expand=True)
file_name data date
0 09066271_142468576_1_Haha_-Haha-haha_2016-10-0... 09066271 2016-10-07
1 09014271_142468576_1_Haha_-Haha-haha_2013-02-1... 09014271 2013-02-18