📜  Python| Pandas Series.from_csv()(1)

📅  最后修改于: 2023-12-03 15:04:21.987000             🧑  作者: Mango

Python | Pandas Series.from_csv()

Pandas Series.from_csv() is a method used to read a CSV file containing data and return it as a Pandas series. The CSV file can be opened from a local path or from a URL. This method is used to create a series object from the data contained in a CSV file.

Syntax
Series.from_csv(path, sep=',', header=0, index_col=0, parse_dates=True, encoding=None, tupleize_cols=False, infer_datetime_format=False)
Parameters
  • path: str, file, or buffer object. This parameter specifies the path of the CSV file or the URL from which the data needs to be read.

  • sep: str, default ‘,’. This parameter specifies the delimiter used in the CSV file.

  • header: int, list of int, default 0. This parameter specifies the row(s) containing the column headers.

  • index_col: int, str, sequence[int/str], or False, default 0. This parameter specifies the column(s) to be used as the index for the Series.

  • parse_dates: boolean or list of int or names, default False. This parameter specifies if the date columns are to be parsed or not. If True, the function tries to parse the index as datetime. If a list of integers or names is given, the function will use these columns as the index.

  • encoding: str, default None. This parameter specifies the encoding type of the data in the CSV file.

  • tupleize_cols: boolean, default False. This parameter specifies if the columns in the CSV file should be parsed as MultiIndexed columns.

  • infer_datetime_format: boolean, default False. This parameter specifies if Pandas should try to infer the format of the datetime columns.

Example
import pandas as pd

# Creating a sample CSV file
with open('test.csv', 'w') as file:
    file.write('Name, Age, Gender\n')
    file.write('Jack, 35, Male\n')
    file.write('Jill, 30, Female\n')
    file.write('Bob, 25, Male\n')

# Reading the CSV file and storing it in a Pandas Series
series = pd.Series.from_csv('test.csv')

# Printing the series
print(series)

Output:

Name      Age Gender
Jack      35.0   Male
Jill      30.0 Female
Bob       25.0   Male
dtype: object

In this example, we have created a sample CSV file containing the information of three people. We read this file using the from_csv() method and stored it in a Pandas Series. Finally, we printed the series to check if it contains the correct data.

Conclusion

The Pandas Series.from_csv() method is a useful tool for reading data from CSV files and storing it in a Pandas Series. By specifying the various parameters offered by this method, we can customize the way in which the data is read and parsed from the CSV file.