Skip to content

Commit 278bc94

Browse files
committed
More pandas docs
1 parent c80502b commit 278bc94

File tree

1 file changed

+113
-11
lines changed

1 file changed

+113
-11
lines changed

docs/hub/datasets-pandas.md

Lines changed: 113 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,44 @@
11
# Pandas
22

33
[Pandas](https://github.com/pandas-dev/pandas) is a widely used Python data analysis toolkit.
4-
Since it uses [fsspec](https://filesystem-spec.readthedocs.io) to read and write remote data, you can use the Hugging Face paths ([`hf://`](/docs/huggingface_hub/guides/hf_file_system#integrations)) to read and write data on the Hub:
4+
Since it uses [fsspec](https://filesystem-spec.readthedocs.io) to read and write remote data, you can use the Hugging Face paths ([`hf://`](/docs/huggingface_hub/guides/hf_file_system#integrations)) to read and write data on the Hub.
55

6-
First you need to [Login with your Hugging Face account](/docs/huggingface_hub/quick-start#login), for example using:
6+
## Load a DataFrame
7+
8+
You can load data from local files or from remote storage like Hugging Face Datasets. Pandas supports many formats including CSV, JSON and Paequet:
9+
10+
```python
11+
>>> import pandas as pd
12+
>>> df = pd.read_csv("path/to/data.csv")
13+
```
14+
15+
To load a file from Hugging Face, the path needs to start with `hf://`. For example, the path to the [stanfordnlp/imdb](https://huggingface.co/datasets/stanfordnlp/imdb) dataset repository is `hf://datasets/stanfordnlp/imdb`. The dataset on Hugging Face contains multiple Parquet files. The Parquet file format is designed to make reading and writing data frames efficient, and to make sharing data across data analysis languages easy. Here is how to load the file `plain_text/train-00000-of-00001.parquet`:
16+
17+
```python
18+
>>> import pandas as pd
19+
>>> df = pd.read_parquet("hf://datasets/stanfordnlp/imdb/plain_text/train-00000-of-00001.parquet")
20+
>>> df
21+
text label
22+
0 I rented I AM CURIOUS-YELLOW from my video sto... 0
23+
1 "I Am Curious: Yellow" is a risible and preten... 0
24+
2 If only to avoid making this type of film in t... 0
25+
3 This film was probably inspired by Godard's Ma... 0
26+
4 Oh, brother...after hearing about this ridicul... 0
27+
... ... ...
28+
24995 A hit at the time but now better categorised a... 1
29+
24996 I love this movie like no other. Another time ... 1
30+
24997 This film and it's sequel Barry Mckenzie holds... 1
31+
24998 'The Adventures Of Barry McKenzie' started lif... 1
32+
24999 The story centers around Barry McKenzie who mu... 1
33+
```
34+
35+
To have more information on the Hugging Face paths and how they are implemented, please refer to the [the client library's documentation on the HfFileSystem](/docs/huggingface_hub/guides/hf_file_system).
36+
37+
## Save a DataFrame
38+
39+
You can save a pandas DataFrame using `to_csv/to_json/to_parquet` to a local file or to Hugging Face directly.
40+
41+
To save the DataFrame on Hugging Face, you first need to [Login with your Hugging Face account](/docs/huggingface_hub/quick-start#login), for example using:
742

843
```
944
huggingface-cli login
@@ -22,26 +57,93 @@ Finally, you can use [Hugging Face paths](/docs/huggingface_hub/guides/hf_file_s
2257
```python
2358
import pandas as pd
2459

25-
df.to_parquet("hf://datasets/username/my_dataset/data.parquet")
60+
df.to_parquet("hf://datasets/username/my_dataset/imdb.parquet")
2661

2762
# or write in separate files if the dataset has train/validation/test splits
2863
df_train.to_parquet("hf://datasets/username/my_dataset/train.parquet")
2964
df_valid.to_parquet("hf://datasets/username/my_dataset/validation.parquet")
3065
df_test .to_parquet("hf://datasets/username/my_dataset/test.parquet")
3166
```
3267

33-
This creates a dataset repository `username/my_dataset` containing your Pandas dataset in Parquet format.
34-
You can reload it later:
68+
## Use Images
69+
70+
From a metadata file containing a "file_name" field for the names or paths to the images:
71+
72+
```
73+
data/ data/
74+
├── metadata.csv ├── metadata.csv
75+
├── img000.png └── images
76+
├── img001.png ├── img000.png
77+
... ...
78+
└── imgNNN.png └── imgNNN.png
79+
```
3580

3681
```python
3782
import pandas as pd
3883

39-
df = pd.read_parquet("hf://datasets/username/my_dataset/data.parquet")
84+
folder_path = "path/to/data/"
85+
df = pd.read_csv(folder_path + "metadata.csv")
86+
for image_path in (folder_path + df["file_name"]):
87+
...
88+
```
4089

41-
# or read from separate files if the dataset has train/validation/test splits
42-
df_train = pd.read_parquet("hf://datasets/username/my_dataset/train.parquet")
43-
df_valid = pd.read_parquet("hf://datasets/username/my_dataset/validation.parquet")
44-
df_test = pd.read_parquet("hf://datasets/username/my_dataset/test.parquet")
90+
Since the dataset is in a supported structure, you can save this dataset to Hugging Face and the Dataset Viewer shows both the metadata and images on HF.
91+
92+
```python
93+
from huggingface_hub import HfApi
94+
api = HfApi()
95+
96+
api.upload_folder(
97+
folder_path=folder_path,
98+
repo_id="username/my_image_dataset",
99+
repo_type="dataset",
100+
)
45101
```
46102

47-
To have more information on the Hugging Face paths and how they are implemented, please refer to the [the client library's documentation on the HfFileSystem](/docs/huggingface_hub/guides/hf_file_system).
103+
Using [pandas-image-methods](https://github.com/lhoestq/pandas-image-methods) you enable `PIL.Image` methods on an image column. It also enables saving the dataset as one single Parquet file containing both the images and the metadata:
104+
105+
```python
106+
import pandas as pd
107+
from pandas_image_methods import PILMethods
108+
109+
pd.api.extensions.register_series_accessor("pil")(PILMethods)
110+
111+
df["image"] = (folder_path + df["file_name"]).pil.open()
112+
df.to_parquet("data.parquet")
113+
```
114+
115+
All the `PIL.Image` methods are available, e.g.
116+
117+
```python
118+
df["image"] = df["image"].pil.rotate(90)
119+
```
120+
121+
## Use Transformers
122+
123+
You can use `transformers` pipelines on pandas DataFrames to classify, generate text, images, etc.
124+
This section shows a few examples.
125+
126+
### Text Classification
127+
128+
```python
129+
from transformers import pipeline
130+
from tqdm import tqdm
131+
132+
pipe = pipeline("text-classification", model="clapAI/modernBERT-base-multilingual-sentiment")
133+
134+
# Compute labels
135+
df["label"] = [y["label"] for y in pipe(x for x in tqdm(df["text"]))]
136+
# Compute labels and scores
137+
df[["label", "score"]] = [(y["label"], y["score"]) for y in pipe(x for x in tqdm(df["text"]))]
138+
```
139+
140+
### Text Generation
141+
142+
```python
143+
from transformers import pipeline
144+
from tqdm import tqdm
145+
146+
p = pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct")
147+
prompt = "What is the main topic of this sentence ? REPLY IN LESS THAN 3 WORDS. Sentence: '{}'"
148+
df["output"] = [y["generated_text"][1]["content"] for y in pipe([{"role": "user", "content": prompt.format(x)}] for x in tqdm(df["text"]))]
149+
```

0 commit comments

Comments
 (0)