Read the planetary data in the text file S12_planet.txt into a Pandas DataFrame. The file will be given in wechat group. Task1, calculate the density of each planet relative to that of the Earth (i.e., the Earth’s density is 1) and add the results as a “density” column in the DataFrame. Print out the DataFrame sorted from the largest to smallest based on the planet diameter. The density formula is � � � � � � � = � / � = 3 � / ( 4 � ∗ � 3 ) density=M/V=3M/(4π∗r 3 ) Task2, read the 2 items in input as "A" and "Standard". A is a "String" and Standard is a "float". Create a Pandas Series that have "A" greater than "Standard", sorted from most to least based on the planet's "A". For example, if input is "year 500", then collect the data of planets whose years are greater than 500. Input A string and a float. Output Task1: DataFrame sorted on diameter Task2: Panda Series sorted on A. Note: You dont need to deal with rounding format. Just let the output as default like that in example.
时间: 2024-01-21 17:02:07 浏览: 230
Pandas数据处理(一)
5星 · 资源好评率100%
Task1:
```python
import pandas as pd
import numpy as np
# Read the planetary data into a DataFrame
df = pd.read_csv('S12_planet.txt', delimiter='\t')
# Calculate the density of each planet relative to that of the Earth
earth_density = 1
df['density'] = (3 * df['mass']) / (4 * np.pi * (df['diameter'] ** 3)) / earth_density
# Sort the DataFrame based on planet diameter
sorted_df = df.sort_values(by='diameter')
# Print the sorted DataFrame
print(sorted_df)
```
Task2:
```python
import pandas as pd
# Read the input values
A = input('Enter string A: ')
Standard = float(input('Enter float Standard: '))
# Create a Pandas Series with planets whose A is greater than Standard
filtered_series = df.loc[df['A'] > Standard, 'A'].sort_values(ascending=False)
# Print the filtered Series
print(filtered_series)
```
注意:以上代码中的 `df` 表示在 Task1 中读入的 DataFrame。如果需要在 Task2 中使用,需要先在代码中进行读取。
阅读全文