python - 如何在 python 中将未处理的字符串添加到 DataFrame 中?

标签 python string pandas dataframe

我有一个字符串对象,如下所示:

Numărul de camere
3 camere
Suprafaţa totală
77 m²
Suprafaţa bucătăriei
11 m²
Tipul clădirii
Dat în exploatare
Etaj
3
Locul de amplasare în casă
In mijlocul casei
Grup sanitar
separat
Balcon/lojă
2
Parcare
acoperită
Încălzire autonomă
✔

这是从网站解析的数据。我想将数据添加到 DataFrame:

df = pd.DataFrame(columns=['ID','Numarul de camere','Suprafata totala',
                       'Suprafata bucatariei','Tipul cladirii','Etaj',
                      'Amplasarea in bloc', 'Grup sanitar', 'Balcon/loja',
                      'Parcare', 'Incalzire autonoma'])

每一第二行字符串都是一个特征,我想将其添加到我的 DataFrame 中的位置。如何做到这一点?

最佳答案

text = """Numărul de camere
3 camere
Suprafaţa totală
77 m²
Suprafaţa bucătăriei
11 m²
Tipul clădirii
Dat în exploatare
Etaj
3
Locul de amplasare în casă
In mijlocul casei
Grup sanitar
separat
Balcon/lojă
2
Parcare
acoperită
Încălzire autonomă
✔ """

#split the string
s = text.split('\n')

import pandas as pd

d = {k:v for k, v in zip(s[0::2],s[1::2])}
df = pd.DataFrame([d])

print df.head()

# if you want to preserve the order of the columns
df = pd.DataFrame.from_items([('Values', s[1::2])], orient='index',columns=s[0::2])

print df.head()

关于python - 如何在 python 中将未处理的字符串添加到 DataFrame 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42585539/

相关文章:

python - 如何在 Django RESTful API 和 React 中使用 csrf_token?

php - 替换字符串中偶数位置的所有字符的最简单方法。

linux - std::string::assign() method from libstdc++.so.6中奇怪的SIGSEGV段错误

python - Pandas:如何查找和连接值

python - 如何在 Pandas 数据框中找到每天的第一个和最后一个值

python - 查找字符串中最短的单词

python - 无法更新 anaconda

python - 将多系列词典保存到 Excel

javascript - 序列化一个奇怪的js对象

python - 在 Pandas 中填充 NaN 的复杂案例