Kat*_*e R 5 python string dataframe pandas
我正在从一堆文件中读取数据并将其存储在数据框中。我想要数据框的一列来指示数据来自哪个文件。如何创建一个反复重复相同字符串的列,而无需手动输入?
我读入的每个文件都有大约 100 个数据点(但每次的数量不同)。当我读入每个数据时,我将沿着 axis=0 连接到数据帧。它应该看起来像这样。
import numpy as np
import pandas as pd
numbers = np.random.randn(5) # this data could be of any length, ~100
labels = np.array(['file01','file01','file01','file01','file01'])
tf = pd.DataFrame()
tf['labels'] = labels
tf['numbers'] = numbers
In [8]: tf
Out[8]:
labels numbers
0 file01 -0.176737
1 file01 -1.243871
2 file01 0.154886
3 file01 0.236653
4 file01 -0.195053
Run Code Online (Sandbox Code Playgroud)
(是的,我知道我可以将“file01”设为列标题并沿 axis=1 附加每个列标题,但有一些原因我不想这样做。)
好了,您的代码已修复!实际上,您可以将单个值放入 DataFrame 构造函数中使用的字典中:)。
import numpy as np
import pandas as pd
filename = 'file01'
numbers = np.random.randn(5) # this data could be of any length, ~100
tf = pd.DataFrame({'labels': filename , 'numbers': numbers})
In [8]: tf
Out[8]:
labels numbers
0 file01 -0.176737
1 file01 -1.243871
2 file01 0.154886
3 file01 0.236653
4 file01 -0.195053
Run Code Online (Sandbox Code Playgroud)