[英]How to get this single column data into data frame with appropriate columns
我正在學習熊貓和數據科學,並且是初學者。 我有如下數據
Rahul
1
2
5
Suresh
4
2
1
Dharm
1
3
4
我希望它在我的數據框中
Rahul 1
2
5
Suresh 4
2
1
Dharm 1
3
4
我如何在不遍歷每一行的情況下實現這一點,因為我有數十萬的數據。 我已經搜索了很多,但除了迭代之外找不到任何東西。 有沒有更好的辦法。
謝謝你的好意和耐心
最好的格式取決於你打算用它做什么,但一個好的起點是這樣做:
鑒於:
Rahul
1
2
5
Suresh
4
2
1
Dharm
1
3
4
正在做:
# Read in the file and call the column 'values':
df = pd.read_table(filepath, header=None, names=['values'])
# Create a new column with names filled in:
df['names'] = df['values'].replace('\d+', np.nan, regex=True).ffill()
# Drop the extra rows:
df = df[df['values'].str.isnumeric()].reset_index(drop=True)
print(df[['names', 'values']])
輸出:
names values
0 Rahul 1
1 Rahul 2
2 Rahul 5
3 Suresh 4
4 Suresh 2
5 Suresh 1
6 Dharm 1
7 Dharm 3
8 Dharm 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.